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一样 省略
    }