Buffer four concepts:
- position: The current position
- mark: the marker position (reset can jump directly to a location)
- limit: permitting position to read
- capacity: Buffer Size
Mobile use of the equivalent position of the buffer (up to limit position) how much you read each move.
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
public class BufferTest {
/**
* 存取过程
*/
@Test
public void saveAndRead(){
String str="test save";
//存过程
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes());
//取过程
//首先切换模式flip()一下
byteBuffer.flip();
//创建一个数组
byte[]dataStr=new byte[byteBuffer.limit()];
byteBuffer.get(dataStr,0,2);//读取缓冲去的字符流到dataStr数组中起始位置0,读2个字节
}
/**
* 常用方法
*/
@Test
public void methods(){
//1.创建一个指定大学的缓冲区
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
//2.put方法存入数据
byteBuffer.put("Hello world".getBytes());
//3.切换读取模式
byteBuffer.flip();
//4.get方法读取缓冲区
byte[] dataStr=new byte[byteBuffer.limit()];
//5.rewind():可重复读
byteBuffer.rewind();
//6.clear清空缓冲区,缓冲区数据依然存在只是 位置被重新置0
byteBuffer.clear();
//7.标记 指针当前记录位置
byteBuffer.mark();
//8.回到标记位置
byteBuffer.reset();
/**
* byteBuffer的4个概念
* position,mark,limit,capacity
* position <= mark <= limit <= capacity
*/
byteBuffer.limit();
byteBuffer.position();
byteBuffer.capacity();
//9.是否有剩余数据
byteBuffer.hasRemaining();
}
}
Note that the get method to read by passing different parameters representing different ways
get () to read a byte
get (byte [] dst) read byte to byte array
get (int index) began to read from that position
get (byte [] dst, int offset, int length) of bytes to read array dst, length bytes to start reading from the offset
Similarly: getChar ()
similar