ByteBuffer的slice()方法

字节缓冲区切片

直接看个例子:

    @Test
    public void test1() {
        byte[] bytes = new byte[]{1,2,3,4,5};
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        //使用slice之前,一般先调用position()和limit()方法,
        byteBuffer.position(2);
        // 2 5 5
        log.info("position:{},limit:{},capacity:{}", byteBuffer.position(), byteBuffer.limit(), byteBuffer.capacity());
        ByteBuffer byteBuffer1 = byteBuffer.slice();
        // 12345->345
        log.info("position:{},limit:{},capacity:{}", byteBuffer.position(), byteBuffer.limit(), byteBuffer.capacity());
        log.info("position:{},limit:{},capacity:{}", byteBuffer1.position(), byteBuffer1.limit(), byteBuffer1.capacity());
        byteBuffer1.put((byte)6);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i]);
        }
        //使用slice()后,再调用arrayOffset()方法时,会出现返回值非0的情况
        //其是对原缓冲区的偏移
        log.info("offset:{}", byteBuffer1.arrayOffset());

    }

输出结果:

2021-01-10 22:46:05 [INFO] position:2,limit:5,capacity:5
2021-01-10 22:46:05 [INFO] position:2,limit:5,capacity:5
2021-01-10 22:46:05 [INFO] position:0,limit:3,capacity:3
2021-01-10 22:46:05 [INFO] offset:2
12645

参考链接:https://www.cnblogs.com/marcotan/p/4256936.html

posted @ 2021-01-10 22:48  HeliusKing  阅读(3706)  评论(0编辑  收藏  举报