1.每当要向里面写东西的时候,要先执行clear()
readBuffer.clear();
SocketChannel channel = (SocketChannel) key.channel();
//这里执行的是对byteBuffer的写操作
int len = channel.read(readBuffer);
2.当要读的时候,要先执行flip()
this.readBuffer.flip();
// 字节数组,保存具体数据的。 Buffer.remaining() -> 是获取Buffer中有效数据长度的方法。
byte[] datas = new byte[readBuffer.remaining()];
// 是将Buffer中的有效数据保存到字节数组中,执行的是对byteBuffer的读操作。
readBuffer.get(datas);
3.进行代码测试:
ByteBuffer buffer = ByteBuffer.allocate(8);
byte[] temp = new byte[]{3,2,1};
// 写入数据之前 : java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]
// pos - 游标位置, lim - 限制数量, cap - 最大容量
System.out.println("写入数据之前 : " + buffer);
// 写入字节数组到缓存
buffer.put(temp);
// 写入数据之后 : java.nio.HeapByteBuffer[pos=3 lim=8 cap=8]
// 游标为3, 限制为8, 容量为8
System.out.println("写入数据之后 : " + buffer);
// 重置游标 , lim = pos ; pos = 0;
buffer.flip();
// 重置游标之后 : java.nio.HeapByteBuffer[pos=0 lim=3 cap=8]
// 游标为0, 限制为3, cap为8
System.out.println("重置游标之后 : " + buffer);
// 清空Buffer, pos = 0; lim = cap;
// buffer.clear();
// get() -> 获取当前游标指向的位置的数据。
// System.out.println(buffer.get());
for(int i = 0; i < buffer.remaining(); i++){
// get(int index) -> 获取指定位置的数据。
int data = buffer.get(i);
System.out.println(i + " - " + data);
}
//读取数据之后 : java.nio.HeapByteBuffer[pos=0 lim=3 cap=8]
System.out.println("读取数据之后 : " + buffer);
buffer.clear();
//清除数据之后:java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]
System.out.println("清除数据之后:" + buffer);
4.源码分析
4.1 向里面写数据时,与position有关
public ByteBuffer put(byte x) { hb[ix(nextPutIndex())] = x; return this; }
final int nextPutIndex() { // package-private if (position >= limit) throw new BufferOverflowException(); return position++; }
4.2 读数据时,还是与position有关
public ByteBuffer get(byte[] dst) { return get(dst, 0, dst.length); }
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; }
public byte get() { return hb[ix(nextGetIndex())]; }
final int nextGetIndex() { // package-private if (position >= limit) throw new BufferUnderflowException(); return position++; }