java - String (bytes[] Charset) 在 Java7 和 Java 8 中返回不同的结果

标签 java character-encoding jdk1.7

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Java87String {

public static void main(String[] args) throws UnsupportedEncodingException {
        // TODO Auto-generated method stub

        //byte[] b = {-101, 53, -51, -26, 24, 60, 20, -31, -6, 45, 50, 103, -66, 28, 114, -39, 92, 23, -47, 32, -5, -122, -28, 79, 22, -76, 116, -122, -54, -122};
        //byte[] b = {-76, -55, 85, -50, 80, -23, 27, 62, -94, -74, 47, -123, -119, 94, 90, 61, -63, 73, 56, -48, -54, -4, 11, 79};

        byte[] b = { -5, -122, -28};

        System.out.println("Input Array :" + Arrays.toString(b));
        System.out.println("Array Length : " + b.length);                       
        String target = new String(b,StandardCharsets.UTF_8);
        System.out.println(Arrays.toString(target.getBytes("UTF-8")));
        System.out.println("Final Key :" + target);

}
}

以上代码在 Java 7 中返回以下输出

Input Array :[-5, -122, -28]
Array Length : 3
[-17, -65, -67]
Final Key :�

相同的代码在 Java 8 中返回以下输出

Input Array :[-5, -122, -28]
Array Length : 3
[-17, -65, -67, -17, -65, -67, -17, -65, -67]
Final Key :���

听起来 Java8 用默认序列 [-17, -65, -67] 替换是正确的。

为什么 JDK 1.7 中的输出和 Any Known bug 存在差异,修复了这个问题?

最佳答案

根据 String JavaDoc :

The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

关于java - String (bytes[] Charset) 在 Java7 和 Java 8 中返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766217/

相关文章:

java - java -fullversion 中的 b 表示什么?

java - 在 junit 测试中模拟 DateFormat 类

java - 安卓java.net.UnknownHostException : Host is unresolved (strategy question)

java - Spring MVC : No mapping found for HTTP request with URI [/hello. jsp]

java - 用Pig将二进制文件存储到hbase

reactjs - JSX 文件中的 " "在某些浏览器中被转换为 "Â"

安卓工作室 - "Unmappable character for encoding UTF-8"

java-javaagent : printing java command use guidelines

java - Apache James 安装问题 - java.lang.UnsupportedClassVersionError :

c++ - Qt 5 编码问题(UTF-8、Windows-1250、Windows-1251)