bytebuffer Java缓冲区标记并在for循环中重置
我见过生产代码,每次都在for循环中标记并放置初始化的缓冲区位置。有必要吗
*/
public static void writeToBuffer(final List<ByteBuffer> attachments, final ByteBuffer buffer) {
for (ByteBuffer buf : attachments) {
buf.mark();
// copy content of buf to buffer
buf.reset();
}
}
# 1 楼答案
是的,这是必要的,如果您希望能够在代码后面的循环中开始读取缓冲区之前返回缓冲区位置
示例:
开始读取缓冲区之前的位置,这是设置标记的位置
x-
//读取缓冲区后,位置(可能)在末尾
X
//调用重置将移回标记位置,以便我们可以再次读取字节
x-
从java doc开始: