Java I/O How to - Convert ByteBuffer to a CharBuffer








Question

We would like to know how to convert ByteBuffer to a CharBuffer.

Answer

       //w w  w.ja v  a2  s  .c o  m

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class MainClass {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });
    bb.rewind();
    CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
    System.out.println("Char Buffer");
    while (cb.hasRemaining())
      System.out.println(cb.position() + " -> " + cb.get());
  }
}

The code above generates the following result.