方法Buffer mark()的作用:在此缓冲区的位置设置标记。
标记有什么作用呢?缓冲区的标记是一个索引,在调用reset()方法时,会将缓冲区的position位置重置为该索引。标记(mark)并不是必需的。定义mark时,不能将其定义为负数,并且不能让它大于position。如果定义了mark,则在将position或limit调整为小于该mark的值时,该mark被丢弃,丢弃后mark的值是-1。如果未定义mark,那么调用reset()方法将导致抛出InvalidMarkException异常。
缓冲区中的mark有些类似于探险或爬山时在关键路口设置“路标”,目的是在原路返回时找到回去的路。
mark的示例代码如下:
public class Test5 { public static void main(String[] args) { byte[] byteArray = new byte[] { 1, 2, 3 }; ByteBuffer bytebuffer = ByteBuffer.wrap(byteArray); System.out.println("bytebuffer.capacity=" + bytebuffer.capacity()); System.out.println(); bytebuffer.position(1); bytebuffer.mark(); // 在位置1设置mark System.out.println("bytebuffer.position=" + bytebuffer.position()); bytebuffer.position(2); // 改变位置 bytebuffer.reset(); // 位置重置 System.out.println(); // 回到位置为1处 System.out.println("bytebuffer.position=" + bytebuffer.position()); } }
程序运行结果如下:
bytebuffer.capacity=3 bytebuffer.position=1 bytebuffer.position=1