ByteBuffer和String相互转换,以及其中发现的问题

public static void main(String[] args) {
        //字符串转ByteBuffer
        //1.1 Buffer.put() 需要手动转为读模式
        ByteBuffer buffer1 = ByteBuffer.allocate(16);
        //追踪getBytes方法的源码发现 默认使用StandardCharsets.UTF_8 不传这个参数也无妨
        buffer1.put("hello".getBytes(StandardCharsets.UTF_8));
        //没有转为读模式 此时打印的东西乱码 会引发一个问题 看2.1打印结果 hello后面跟了一个乱码的字符
        System.out.println((char) buffer1.get());

        //1.2 使用Charset.encode("") buffer2 自动转为读模式
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");
        //打印 h
        System.out.println((char) buffer2.get());

        //1.3 ByteBuffer.wrap(byte[] sr) buffer3 自动转为读模式
        ByteBuffer buffer3 = ByteBuffer.wrap("hello".getBytes());
        // 打印 h
        System.out.println((char)buffer3.get());


        //2 ByteBuffer转字符串
        //2.1 Buffer.put()
        buffer1.flip();
        String s = StandardCharsets.UTF_8.decode(buffer1).toString();
        //hello后面跟了一个乱码的字符
        System.out.println(s);

        //2.2 Charset.encode("")
        String s1 = StandardCharsets.UTF_8.decode(buffer2).toString();
        //在1.2时调用了一次get 所以打印为ello
        //推断出decode方法获取的是buffer2中未读取过的数据即从position开始,而非buffer2中全部数据
        System.out.println(s1);
        //调用rewind position重置 重头开始读buffer2 打印出hello
        buffer2.rewind();
        String s3 = StandardCharsets.UTF_8.decode(buffer2).toString();
        System.out.println(s3);
        //2.3  ByteBuffer.wrap() 转 String 同2.2一样 省略
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值