ByteBuffer.clear()(没有清除内容)

概述:直接看clear()官方介绍

Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. 

Invoke this method before using a sequence of channel-read or put operations to fill this buffer. For example: 

 buf.clear();     // Prepare buffer for reading
 in.read(buf);    // Read data
This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case. 

Returns:
This buffer
关键一句就是This method does not actually erase the data in the buffer ,它并没有清除数据,只是把光标设置第一个位置上,限制变成容量大小,这里需要解释一下position、limit、capacity


还不得不介绍ByteBuffer中flip(), rewind()方法和clear()区别

clear() 简单理解就是复位(Reset) 但不清除数据(position=0, limit=capacity)

flip() 彩排(先预演一遍,然后在从前读到当前位置,将当前位置设置limit值,position=0)

rewind() 再来一次(重复读取一次, 只是将position移到第一位置)

具体可以参考详解:http://blog.sina.com.cn/s/blog_68af3f090100sbo4.html

还解释一下:arrayOffset() (简单理解当前position移动相对0的位置) 以此作为相对位置

现在执行clear()方法,此时位置0 , 那么 arrayOffset()=0

根据这个结论,我们就可以获取最新写数据,多余数据将会不会读取(虽然clear()没有清除数据)

//将缓冲区清空以备下次读取  

receivebuffer.clear();  

//读取客户端发送来的数据到缓冲区中  
count = client.read(receivebuffer);  

String str = new String(receivebuffer.array(),receivebuffer.arrayOffset(), 
receivebuffer.arrayOffset()+receivebuffer.position(), "UTF-8");


receivebuffer.position():就是当前写入位置。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值