首页 > 其他 > 详细

ByteBuffer使用实例

时间:2019-10-25 01:00:33      阅读:126      评论:0      收藏:0      [点我收藏+]

  ByteBuffer作为老牌的字节流处理对象,这里举个小例子说明下用法,直接上代码:

package com.wlf.netty.nettyserver;

import org.junit.Assert;
import org.junit.Test;

import java.nio.ByteBuffer;

public class ByteBufferTest {

    @Test
    public void byteBufferTest() {

        // 写入消息体
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.putInt(0xabef0101);
        byteBuffer.putInt(1024); // 今天过节
        byteBuffer.put((byte) 1);
        byteBuffer.put((byte) 0);

        // 读取消息头,因为写完后position已经到10了,所以需要先反转为0,再从头读取
        byteBuffer.flip();
        printDelimiter(byteBuffer);

        // 读取length
        printLength(byteBuffer);

        // 继续读取剩下数据
        byteBuffer.get();
        byteBuffer.get();
        printByteBuffer(byteBuffer);

        // 我再反转一下,我还可以从头开始读
        byteBuffer.flip();
        printDelimiter(byteBuffer);

        // clear清空一下,再从头开始读
        byteBuffer.clear();
        printDelimiter(byteBuffer);

        // rewind重绕一下
        byteBuffer.rewind();
        printDelimiter(byteBuffer);

        // mark标记一下
        byteBuffer.mark();

        // 再读取length
        printLength(byteBuffer);

        // reset重置,回到读取delimiter的地方
        byteBuffer.reset();
        printByteBuffer(byteBuffer);
    }

    private void printDelimiter(ByteBuffer buf) {
        int newDelimiter = buf.getInt();
        System.out.printf("delimeter: %s\n", Integer.toHexString(newDelimiter));
        printByteBuffer(buf);
    }

    private void printLength(ByteBuffer buf) {
        int length = buf.getInt();
        System.out.printf("length: %d\n", length);
        printByteBuffer(buf);
    }

    private void printByteBuffer(ByteBuffer buf) {
        System.out.printf("position: %d, limit: %d, capacity: %d\n", buf.position(), buf.limit(), buf.capacity());
    }
}

  输出结果:

delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 10, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 4, limit: 10, capacity: 10

Process finished with exit code 0

 

ByteBuffer使用实例

原文:https://www.cnblogs.com/wuxun1997/p/11735826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!