字符集的疑惑。
在《Java解惑》一书中提及默认字符集,即不指定字符集,进行类型转换所带来的“莫名其妙”。
书中示例代码:
byte bytes[] = new byte[256];
for(int i = 0; i<256; i++)
bytes[i] = (byte)i;
String str = new String(bytes);
for ( int i = 0; n = str.length(); i < n; i++)
System.out.print((int)str.charAt(i) + " "); [1]
这个运行结果在不同机器上可能有不同结果,原因是J2SE runtime 的默认字符集以来系统配置。
在JDK Doc中:
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
所以使用:
String(byte[] bytes,Charset charset)
Constructs a new String by decoding the specified array of bytes using the specifiedcharset.
这样可以保证转换的可控性。
Java字符集转换之谜
本文探讨了Java中默认字符集在字符串转换时可能导致的问题。通过一个简单的示例代码展示了不同系统配置下运行结果的差异,并提出了指定字符集来确保转换一致性的解决方案。

800

被折叠的 条评论
为什么被折叠?



