ByteBuffer.asCharBuffer打印字符串乱码

背景

下面代码会直接输出乱码。缘由是:getBytes须要指定字符编码java

ByteBuffer byteBuffer = ByteBuffer.wrap("开源中国".getBytes());

CharBuffer buffer = byteBuffer.asCharBuffer();

System.out.println(buffer.toString());

修改后就能符合预期:数组

ByteBuffer byteBuffer = ByteBuffer.wrap("开源中国".getBytes(StandardCharsets.UTF_16));

CharBuffer buffer = byteBuffer.asCharBuffer();

System.out.println(buffer.toString());

缘由

字符编码和编码的方式不一致致使的。编码

  1. getBytes 其实就是把字符串编码按照默认的UTF-8进行编码称为字节数组(看源码可知).code

  2. byteBuffer.asCharBuffer()也就是转为UTF-8的CharBuffer。JAVA内部使用的是UTF-16字符串

下面会证实:get

ByteBuffer byteBuffer = ByteBuffer.wrap("开源中国".getBytes());
System.out.println(byteBuffer.limit()); // 12 每一个字符3字节

// 把 ByteBuffer 使用UTF-8解码为UTF-16的CharBuffer而后toString输出
System.out.println(StandardCharsets.UTF_8.decode(byteBuffer).toString()); // 结果能正常输出

byteBuffer.rewind();
CharBuffer buffer = byteBuffer.asCharBuffer();

System.out.println(buffer.toString());

小结

  1. JAVA要输出CharBuffer或者char数组,会直接认为是UTF-16编码来获取对应的代码点,最终找到映射的字符源码

  2. String.getBytes:使用默认编码UTF-8(Windows会不同)进行编码为对应字节it

相关文章
相关标签/搜索