Java I/O How to - Get array out of CharBuffer








Question

We would like to know how to get array out of CharBuffer.

Answer

import java.nio.CharBuffer;
/*ww w.ja v  a  2s .  c om*/
public class MainClass {
  public static void main(String[] argv) throws Exception {
    CharBuffer cb = CharBuffer.allocate(100);

    cb.put("This is a test String");

    cb.flip();

    System.out.println("hasArray() = " + cb.hasArray());

    char[] carray = cb.array();

    System.out.print("array=");

    for (int i = 0; i < carray.length; i++) {
      System.out.print(carray[i]);
    }

    System.out.println("");
    System.out.flush();
  }
}

The code above generates the following result.