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]序列替换。
为什么JDK1.7中的输出和任何已知的bug存在差异,从而解决了这个问题?
发布于 2016-09-29 20:17:01
根据字符串JavaDoc
当给定字节在给定字符集中无效时,此构造函数的行为未指定。当需要对解码过程进行更多的控制时,应该使用CharsetDecoder类。
发布于 2016-09-29 12:13:48
我认为(-5, -122, -28)是一个无效的UTF-8字节序列,所以JVM在这种情况下可以输出任何东西。如果它是有效的,那么不同的Java版本可能会显示相同的输出。
这个特定的字节序列有意义吗?只是好奇
https://stackoverflow.com/questions/39766217
复制相似问题