package com.stu.buffer;
import org.junit.Test;
import java.nio.ByteBuffer;
/**
* 一、缓存区(Buffer):在 Java NIO 中负责数据的存取.缓存区就是数组。用于存储不同的数据类型的数据。
*
* 根据数据类型不同(boolean除外),提供了相对应的缓存区。
* ByteBuffer
* CharBuffer
* ShortBuffer
* IntBuffer
* LongBuffer
* FloatBuffer
* DoubleBuffer
* 上述缓存区的管理方式几乎一致,都是通过 allocate() 获取缓存区.
* 二、缓存区存取数据的两个核心方法。
* put():存入数据到缓存区
* get(): 获取缓存区中数据
*
* 四、缓存区中的四个核心属性。
* 1. capacity: 容量,标识缓存区最大存储的容量,一但声明不能改变.
* limit: 界限,标识缓存区中可以操作数据的大小, (limit后数据不能进行读写)
* position:位置,标识缓存区中正在操作数据的位置
*
* mark: 标记,表示记录当前position的位置,可以推过reset() 恢复到mark位置
*
* 0 <= position <= limit <= capacity
*/
public class TestBuffer {
@Test
public void test0() {
String str = "abcde";
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
byte[] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes, 0, 2);
System.out.println(new String(bytes, 0, 2));
System.out.println(byteBuffer.position());
// mark(): 标记一下
byteBuffer.mark();
byteBuffer.get(bytes, 2,2);
System.out.println(new String(bytes, 2, 2));
System.out.println("位置:" + byteBuffer.position());
// 重置 恢复到mark() 的位置
byteBuffer.reset();
System.out.println("位置:" + byteBuffer.position());
// 判断缓存区中是否还有未知的数据
if (byteBuffer.hasRemaining()) {
System.out.println("缓存中剩余的数据:" + byteBuffer.remaining());
}
}
@Test
public void test1() {
String str = "abcde";
// 1. 分配一个指定大小的缓存区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
System.out.println("----------allocate ------------------");
System.out.println(byteBuffer.capacity());
System.out.println(byteBuffer.limit());
System.out.println(byteBuffer.position());
// 2. 利用put()方法存入数据到缓存区中
byteBuffer.put(str.getBytes());
System.out.println("----------put ---------------------");
System.out.println(byteBuffer.capacity());
System.out.println(byteBuffer.limit());
System.out.println(byteBuffer.position());
// 3. 切换读取数据模式
byteBuffer.flip();
System.out.println("----------put ---------------------");
System.out.println(byteBuffer.capacity());
System.out.println(byteBuffer.limit());
System.out.println(byteBuffer.position());
// 4. 利用get()读取缓存区中的数据
byte [] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes);
System.out.println(new String(bytes, 0, bytes.length));
// 5. rewind():可重复读
byteBuffer.rewind();
System.out.println("---------- rewind ---------------------");
System.out.println(byteBuffer.capacity());
System.out.println(byteBuffer.limit());
System.out.println(byteBuffer.position());
// 6 clear()(清空缓存区,缓存区中的数据依然存在,但是处于被遗忘状态
byteBuffer.clear();
System.out.println("---------- clear() ---------------------");
System.out.println(byteBuffer.capacity());
System.out.println(byteBuffer.limit());
System.out.println(byteBuffer.position());
System.out.println(byteBuffer.get(3));
System.out.println((char)byteBuffer.getChar());
System.out.println((char)byteBuffer.get());
}
}
学自,b站尚硅谷