Java I/O How to - Fill String to CharBuffer








Question

We would like to know how to fill String to CharBuffer.

Answer

        //  w  ww. j  ava2 s.co m

import java.nio.CharBuffer;

public class MainClass {
  public static void main(String[] argv) throws Exception {
    CharBuffer buffer = CharBuffer.allocate(100);

    String string = "asdf";

    for (int i = 0; i < string.length(); i++) {
      buffer.put(string.charAt(i));
    }

    buffer.flip();
    drainBuffer(buffer);
    buffer.clear();
  }

  private static void drainBuffer(CharBuffer buffer) {
    while (buffer.hasRemaining()) {
      System.out.print(buffer.get());
    }

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

The code above generates the following result.