package nio
import java.nio.ByteBuffer
import org.junit.Test
public class buffer {
@Test
public void test1(){
String str="abc"
//1、分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024)
System.out.println("---------allocate()----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
//2、利用put() 存入数据到缓冲区中
buf.put(str.getBytes())
System.out.println("---------put()写数据模式----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
//3、切换成读取数据的模式
buf.flip()
System.out.println("---------flip() 切换到读数据模式----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
//4、利用get读取缓冲区中的数据
byte[] dst=new byte[buf.limit()]
buf.get(dst)
System.out.println(new String(dst,0,dst.length))
System.out.println("---------get()读取缓冲区的数据----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
//5、rewind() : 可重复读
buf.rewind()
System.out.println("---------rewind()----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
//6、清空缓冲区,但是缓冲区里面的数据还在,只不过这些数据处于“被遗忘”状态
buf.clear()
System.out.println("---------clear()----------")
System.out.println(buf.position())
System.out.println(buf.limit())
System.out.println(buf.capacity())
System.out.println((char)buf.get())
}
@Test
public void test2(){
String str="abcde"
ByteBuffer buf = ByteBuffer.allocate(1024)
buf.put(str.getBytes())
buf.flip()
byte[] dst=new byte[buf.limit()]
buf.get(dst,0,2)
System.out.println(new String(dst,0,2))
System.out.println(buf.position())
buf.mark()
buf.get(dst,2,2)
System.out.println(new String(dst,2,2))
System.out.println(buf.position())
buf.reset()
System.out.println(buf.position())
//判断缓冲区中是否还有可以操作的数据
if(buf.hasRemaining()){
//获取缓冲区中可以操作的数据的数量
System.out.println(buf.remaining())
}
}
}