字节操作


<!--创建方式 1 -->

 ByteBuf buffer = Unpooled.buffer(10);
 
<!--创建方式 2-->
 
 ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
 
  int len = byteBuf.readableBytes(); //可读的字节数  12
 System.out.println("len=" + len);
    
 //使用for取出各个字节
 for (int i = 0; i < len; i++) {
     System.out.println((char) byteBuf.getByte(i)); // 强行转为字符串,否则会直接打印ASCII码
 }
    
//按照某个范围读取
 System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8")));
 System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8")));
            

 ByteBuf byteBuf1 = Unpooled.copiedBuffer(byteBuf);

ByteBuf转字节数组

byte[] bytes = ByteBufUtil.getBytes(byteBuf1);

字节读取

    <!--读取--> 
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        byte[] newBytes = new byte[bytes.length];
        while (inputStream.read(newBytes)!=-1){
            inputStream.close();
            System.out.println(new String(newBytes));
        }

       <!--读取一部分-->
        ByteArrayInputStream inputStream1 = new ByteArrayInputStream(bytes,2,5);
        byte[] newBytes1 = new byte[bytes.length];
        while (inputStream1.read(newBytes1)!=-1){
            inputStream1.close();
            System.out.println(new String(newBytes1));
        }

岁月峥嵘走过
34 声望2 粉丝