使用UTF-8编码创建字符串时存在不一致性。
运行此代码:
public static void encodingIssue() throws IOException {
byte[] array = new byte[3];
array[0] = (byte) -19;
array[1] = (byte) -69;
array[2] = (byte) -100;
String str = new String(array, "UTF-8");
for (char c : str.toCharArray()) {
System.out.println((int) c);
}
}
在Java 1.8.0_20(以及早期版本)中,我们得到了以下结果
65533
在Java 1.7和1.6上,我们得到了正确的结果:
57052
你遇到过这个错误吗?有没有解决方法?
对于 Shift_JIS、JIS_X0212-1990、x-IBM300、x-IBM834、x-IBM942、x-IBM942C、x-JIS0208 等编码也存在这种不一致的情况,但显然 UTF-8 更加紧急。