Java I/O How to - Test the effects of buffer flipping








Question

We would like to know how to test the effects of buffer flipping.

Answer

import java.nio.CharBuffer;
//from  w w w  . j av a 2 s.  c o  m
public class Main {
  public static void main(String[] argv) throws Exception {
    CharBuffer cb = CharBuffer.allocate(15);

    cb.put("Hello World");
    println(cb);

    cb.flip();
    println(cb);

    cb.flip();
    println(cb);
  }

  private static void println(CharBuffer cb) {
    System.out.println("pos=" + cb.position() + ", limit=" + cb.limit()
        + ": '" + cb + "'");
  }
}

The code above generates the following result.