NIO buffer (Buffer) access and common methods

Buffer four concepts:

  1. position: The current position
  2. mark: the marker position (reset can jump directly to a location)
  3. limit: permitting position to read
  4. 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

 

 

 

 

 

Published 242 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/103828612