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());
}
}