// 注 北字的UTF-8编码是E5 8C 97 GBK编码B1 B1
byte[] b = new byte[]{(byte)0xe5, (byte)0x8c, (byte)0x97};
String s2 = new String(b, "UTF-8");
System.out.println(s2);
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes()));
System.out.println("-----");
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes("UTF-8")));
输出为:
北
In Hex:
0xb1 0xb1
-----
In Hex:
0xe5 0x8c 0x97
System.out.println(s2);
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes()));
System.out.println("-----");
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes("UTF-8")));
输出为:
北
In Hex:
0xb1 0xb1
-----
In Hex:
0xe5 0x8c 0x97
String s2 = new String("北".getBytes(), "UTF-8");
System.out.println(s2);
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes()));
System.out.println("-----");
System.out.println(ToStringUtil.byteArrayToHexString(s2
.getBytes("UTF-8")));
输出为:
??
In Hex:
0x3f 0x3f
-----
In Hex:
0xef 0xbf 0xbd 0xef 0xbf 0xbd
也就是说:
采用public String(byte bytes[], String charsetName)方式创建String时 byte[]的编码 和charsetName 应该是一致的
String在VM存储的字符集应该是unicode,getBytes 按指定字符集或者缺省字符集进行转换输出。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26273052/viewspace-1059814/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26273052/viewspace-1059814/