public class App {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(88);
String value = "权威指南";
buffer.put(value.getBytes());
System.out.println(buffer.capacity());
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println("===================");
buffer.flip();
int remaining = buffer.remaining();
System.out.println(buffer.capacity());
System.out.println(buffer.position());
System.out.println(buffer.limit());
byte[] vArray = new byte[remaining];
ByteBuffer bb = buffer.get(vArray);
String dcode = new String(vArray);
System.out.println(dcode);
}
}
以上代码的结果:
88
12
88
===================
88
0
12
权威指南
1、从代码运行结果可以分析出,开始初始化capacity,position,limit分别是88,12,88,
2、从源码角度解析:
a、 public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
执行new HeapByteBuffer(capacity, capacity); capacity赋值为88,limit为88
执行buffer.put(value.getBytes()); position(position() + length);将position赋值为12
b、flip()方法实现:
<pre name="code" class="java"> public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
将limit赋值为12,position赋值为0,这样就可以正确读取数据
之前put的时候发生:
public ByteBuffer put(byte[] src, int offset, int length) {
checkBounds(offset, length, src.length);
if (length > remaining())
throw new BufferOverflowException();
int end = offset + length;
for (int i = offset; i < end; i++)
this.put(src[i]);
return this;
}
这里的end是12
读取的时候也要从0,12开始读取,不然会错误读,以下是读取源码:
public ByteBuffer get(byte[] dst, int offset, int length) {
checkBounds(offset, length, dst.length);
if (length > remaining())
throw new BufferUnderflowException();
int end = offset + length;
for (int i = offset; i < end; i++)
dst[i] = get();
return this;
}