clear()方法:清空缓冲区。但是缓冲区的数据依然存在,但是这些数据处于被遗忘的状态。package com.gwolf;import org.junit.Test;import java.nio.ByteBuffer;public class TestBuffer { @Test public void test1(){ //分配一个指定大小的缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); System.out.println('----------allocate()-------------'); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit());; System.out.println(byteBuffer.capacity()); //利用put方法存入数据到缓冲区中 String str = 'abcde'; byteBuffer.put(str.getBytes()); System.out.println('----------put()-------------'); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit());; System.out.println(byteBuffer.capacity()); //3、切换成读取数据模式 byteBuffer.flip(); System.out.println('----------flip()-------------'); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit());; System.out.println(byteBuffer.capacity()); //4、利用get()读取缓冲区的数据 byte[] dst = new byte[byteBuffer.limit()]; byteBuffer.get(dst); System.out.println(new String(dst,0,dst.length)); byteBuffer.clear(); System.out.println('----------clear()-------------'); System.out.println(byteBuffer.position()); System.out.println(byteBuffer.limit());; System.out.println(byteBuffer.capacity()); }}
查看执行clear方法之后position、limit、capacity的位置大小
创建一个ByteBuffer,代码如下:public void test2() { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put('abced'.getBytes()); buffer.flip(); byte[] dst = new byte[buffer.limit()]; buffer.get(dst,0,2); System.out.println(new String(dst,0,2)); System.out.println(buffer.position()); }
查看打印结果。
mark()方法:标识记录当前position的位置,可以通过reset()回复到mark的位置。 buffer.mark(); buffer.get(dst,2,2); System.out.println(new String(dst,2,2)); System.out.println(buffer.position());
查看现在position的位置是多少
使用reset()恢复到mark位置buffer.reset();System.out.println(buffer.position());