下面以一个实例介绍 NIO 的 Buffer
public class TestBuffer {
@Test
public void testBuffer() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println("----------------- allocate ---------------");
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
buffer.put("abcdefgh".getBytes());
System.out.println("----------------- put ---------------");
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
buffer.flip();
System.out.println("----------------- flip ---------------");
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
System.out.println("----------------- get ---------------");
System.out.println("data : " + new String(bytes));
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
buffer.rewind();
System.out.println("----------------- rewind ---------------");
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
buffer.clear();
System.out.println("----------------- clear ---------------");
System.out.println("position" + " : " + buffer.position());
System.out.println("limit" + " : " + buffer.limit());
System.out.println("capacity" + " : " + buffer.capacity());
System.out.println((char)buffer.get());
}
@Test
public void testDirectBuffer() {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
System.out.println(buffer.isDirect());
}
@Test
public void testMark() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("abcdefgh".getBytes());
buffer.flip();
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes, 0, 2);
System.out.println("data : " + new String(bytes, 0, 2));
System.out.println("position" + " : " + buffer.position());
buffer.mark();
buffer.get(bytes, 2, 2);
System.out.println("data : " + new String(bytes, 2, 2));
System.out.println("position" + " : " + buffer.position());
buffer.reset();
System.out.println("--------- after reset --------");
System.out.println("position" + " : " + buffer.position());
if (buffer.hasRemaining()) {
System.out.println(buffer.remaining());
}
}
}