Java I/O How to - Slice CharBuffer








Question

We would like to know how to slice CharBuffer.

Answer

import java.nio.CharBuffer;
//  ww  w .j  a va  2 s  . c  o  m
public class MainClass {
  public static void main(String[] argv) throws Exception {
    CharBuffer buffer = CharBuffer.allocate(8);
    buffer.position(3).limit(5);
    CharBuffer sliceBuffer = buffer.slice();

    println(buffer);
    println(sliceBuffer);

    char[] myBuffer = new char[100];
    CharBuffer cb = CharBuffer.wrap(myBuffer);

    cb.position(12).limit(21);

    CharBuffer sliced = cb.slice();

    println(cb);
    println(sliced);
  }

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

The code above generates the following result.