在 java nio 的 bytebuffer 中,mark() 用于记录当前 position 的位置,以便后续通过 reset() 恢复到该位置。具体做法是:在修改 position 之前调用 mark(),需要恢复时调用 reset();若 position 超出标记范围或标记未设置,会抛出异常。

mark() 与 reset() 的基本用法是什么
mark() 保存当前 position,reset() 将 position 重置为标记值。示例代码演示了读取部分数据后回退的操作。

import java.nio.ByteBuffer;
public class MarkResetDemo {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put((byte) 'A');
buffer.put((byte) 'B');
buffer.put((byte) 'C');
buffer.flip(); // position=0, limit=3
buffer.mark(); // mark=0
byte first = buffer.get(); // position=1
System.out.println("Read: " + first); // A
buffer.reset(); // position=0
byte second = buffer.get(); // position=1
System.out.println("Re-read: " + second); // A
}
}
预期输出:
Read: A
Re-read: A
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
clear() 对 mark 有什么影响
clear() 会丢弃 mark,将 position 设为 0,limit 设为容量。因此,若在 clear() 后调用 reset() 会抛出 InvalidMarkException。

import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;
public class ClearMarkDemo {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put((byte) 'X');
buffer.flip();
buffer.mark(); // mark=0
buffer.clear(); // mark discarded, position=0, limit=10
try {
buffer.reset(); // throws InvalidMarkException
} catch (InvalidMarkException e) {
System.out.println("Mark is invalid after clear()");
}
}
}
预期输出:
Mark is invalid after clear()
当 position 超过 mark 后再 reset() 会发生什么
如果 position 在标记之后被移动但未超过 limit,reset() 仍可正常回退到标记位置。但若 position 被设为大于 mark 的值(如直接调用 position(int)),reset() 依然有效,只要标记未被清除。只有当 mark 被清除(如 clear())或 position 超出 mark 且标记失效时才会出错。实际上,reset() 只检查标记是否存在,不检查 position 是否曾超过它。因此,即使 position 曾移动到 5,只要标记还在,reset() 就能回到标记处。

















