Convert ByteBuffer to CharBuffer : CharBuffer « File « Java Tutorial






import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;

/**
 * Test asCharBuffer view.
 */
public class MainClass {
  public static void main(String[] argv) throws Exception {
    ByteBuffer byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
    CharBuffer charBuffer = byteBuffer.asCharBuffer();

    byteBuffer.put(0, (byte) 0);
    byteBuffer.put(1, (byte) 'H');
    byteBuffer.put(2, (byte) 0);
    byteBuffer.put(3, (byte) 'i');
    byteBuffer.put(4, (byte) 0);
    byteBuffer.put(5, (byte) '!');
    byteBuffer.put(6, (byte) 0);

    println(byteBuffer);
    println(charBuffer);

    // now slice it differently
    byteBuffer.position(4);
    charBuffer = byteBuffer.asCharBuffer();

    println(byteBuffer);
    println(charBuffer);
  }

  // Print info about a buffer
  private static void println(Buffer buffer) {
    System.out.println("pos=" + buffer.position() + ", limit=" + buffer.limit() + ", capacity="
        + buffer.capacity() + ": '" + buffer.toString() + "'");
  }
}
/*
*/
pos=0, limit=7, capacity=7: 'java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]'
pos=0, limit=3, capacity=3: 'Hi!'
pos=4, limit=7, capacity=7: 'java.nio.HeapByteBuffer[pos=4 lim=7 cap=7]'
pos=0, limit=1, capacity=1: '!'








11.43.CharBuffer
11.43.1.Buffer Equality
11.43.2.Use CharBuffer
11.43.3.Convert ByteBuffer to a CharBuffer
11.43.4.Use while loop to read a CharBuffer
11.43.5.Save and read text using FileChannel with CharBuffer
11.43.6.Test the effects of buffer flipping
11.43.7.Test buffer duplication
11.43.8.Create a CharBuffer and put in some string
11.43.9.Buffer slice
11.43.10.Wrap a char array to a CharBuffer
11.43.11.Flip a CharBuffer
11.43.12.Get array out of CharBuffer
11.43.13.Convert ByteBuffer to CharBuffer
11.43.14.Fill String to CharBuffer
11.43.15.CharBuffer warps a ByteBuffer