ByteBuf 读取字节数组数据

1.数据准备及代码

ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();//声明一个bytebuf 对象
byteBuf.writeByte(1);//第一位置存放数字1(占用1个字节)
byteBuf.writeShort(0);//第二位置存放数字 0(占用2个字节) ,这里是打算做长度
String temp = "我是谁";//需要获取的数据
byteBuf.writeBytes(temp.getBytes());//获取字节数组
byteBuf.setShort(1,byteBuf.readableBytes());//设置第二位置的长度,也就是整个byteBuf对象的长度
get(byteBuf);//get方法解析

方法:

public static void get(ByteBuf in){
    int inv = in.readerIndex();
    int first =in.getByte(inv);
    inv++;
    int length = in.getShort(inv);
    inv+=2;
    // 减3 是因为前面是获取到总长度,前面占用了byte + short = 1+2=3
    byte[] data = new byte[length - 3];//数据大小
    in.getBytes(inv, data);
    try {
        String str = new String(data, 0, data.length, "utf-8");
        System.out.println(str);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

2.执行结果

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值