概述:直接看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():就是当前写入位置。