Confusion in Java 2

来源:互联网 发布:vncserver的端口 编辑:程序博客网 时间:2024/05/20 22:29

字符集的疑惑。

在《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.

这样可以保证转换的可控性。

原创粉丝点击