您的位置:首页 > 编程语言

NIO编程(mark与reset用法)

2018-02-20 15:15 232 查看

mark与reset用法

标记是一个索引,通过Buffer中的mark()方法指定Buffer中一个特定的position,之后可以通过调用reset()方法恢复到这个position。

[b]代码用例[/b]

public class BufferTest {
public static void main(String[] args) {

ByteBuffer allocate = ByteBuffer.allocate(1024);
allocate.put("yswKnight".getBytes());
System.out.println("------开启读取模式------");
allocate.flip();
byte[] bytes = new byte[allocate.limit()];
//获取缓冲区数据
allocate.get(bytes,0,2);
//mark是一个索引,通过此方法指定Buffer中一个特定的position
allocate.mark();
System.out.println(new String(bytes,0,2));
System.out.println(allocate.position());

//这时重新获取缓冲区数据,position为4(get中获取到的第三个参数加起来的值)
allocate.get(bytes,3,2);
System.out.println(new String(bytes,3,2));
System.out.println(allocate.position());

//然后可以通过调用reset()方法恢复到这个position
allocate.reset();
System.out.println("------重置恢复到mark位置------");
System.out.println(allocate.position());

}
}


[b]运行结果[/b]

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: