在学习Java NIO中看到关于Buffer的部分时提到bytebuffer调用clear()方法不会真正的删除掉buffer中的数据,只是把position移动到最前面,同时把limit调整为capacity。源码:
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
官方概述: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 caseClears this buffer. The position is set to zero, the limit is set to * the capacity, and the mark is discarded. *
关键一句就是 This method does not actually erase the data in the buffer
,它并没有清除数据,只是把光标设置第一个位置上,限制变成容量大小。
调用clear()方法:position将被设回0,limit设置成capacity,换句话说,Buffer看起来被清空了,其实Buffer中的数据并未被清除,只是这些标记告诉我们可以从哪里开始往Buffer里写数据。
如果Buffer中有一些未读的数据,调用clear()方法,数据将“被遗忘”,意味着不再有任何标记会告诉你哪些数据被读过,哪些还没有。
如果Buffer中仍有未读的数据,且后续还需要这些数据,但是此时想要先写些数据,那么使用 compact()
方法。compact()方法将所有未读的数据拷贝到Buffer起始处。然后将position设到最后一个未读元素正后面。limit属性依然像clear()方法一样,设置成capacity。现在Buffer准备好写数据了,但是不会覆盖未读的数据。
另有文章:
- https://blog.youkuaiyun.com/pfnie/article/details/52829549
- https://blog.youkuaiyun.com/qq_22701869/article/details/107091427