// 创建一个 1 KB 大小的缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024);
private int mark = -1; private int position = 0; private int limit; private int capacity;
ByteBuffer buf = ByteBuffer.allocate(5);
// 写模式 byteBuffer.put("Tom".getBytes());
// 读模式 byteBuffer.get();
// 分配 1 KB 大小的缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); System.out.println("=============allocate()==========="); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity());
System.out.println("=============put()==========="); String name = "abcde"; byteBuffer.put(name.getBytes()); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity());
System.out.println("============flip()==========="); byteBuffer.flip(); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity());
System.out.println("============get()==========="); byte[] dst = new byte[byteBuffer.limit()]; byteBuffer.get(dst); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity()); System.out.println(new String(dst));
System.out.println("============rewind()==========="); byteBuffer.rewind(); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity());
System.out.println("============clear()==========="); byteBuffer.clear(); System.out.println("position = " byteBuffer.position()); System.out.println("limit = " byteBuffer.limit()); System.out.println("capacity = " byteBuffer.capacity());
ByteBuffer buf = ByteBuffer.allocate(5); buf.put("abcde".getBytes()); buf.flip(); byte[] dst = new byte[buf.limit()]; buf.get(dst, 0, 2); // get(byte[] dst, int offset, int length) System.out.println("第一次取出结果:" new String(dst)); System.out.println("position:" buf.position()); // mark()标记 buf.mark(); buf.get(dst, 2, 2); // get(byte[] dst, int offset, int length) System.out.println("第二次取出结果:" new String(dst)); System.out.println("position:" buf.position()); // 恢复到mark buf.reset(); System.out.println("reset 恢复到 mark 位置"); System.out.println("position:" buf.position());
// remaining() 获取缓冲区中还可以操作的数量 if (buf.hasRemaining()) { System.out.println(buf.remaining()); System.out.println("limit - position = " (buf.limit() - buf.position())); }