ByteBuffer 操作心得

 

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++;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值