情况如下:
String str = "中";
String newStr = new String(str.getBytes("GBK"), "UTF-8");
newStr还能还原成str吗?感觉是不能了。
情况如下:
String str = "中";
String newStr = new String(str.getBytes("GBK"), "UTF-8");
newStr还能还原成str吗?感觉是不能了。
[color=red]UTF-8是可变长度编码,就是说一个英文字符占用一个字节,而对于汉字是占用三个字节。[/color]
str.getBytes("GBK")指的是:[color=red]使用GBK将str字符串解码为字节序列。[/color]
String(byte[] bytes,String charsetName),指的是:
构造一个新的 String,方法是使用指定的字符集解码指定的字节数组。
只要明白以上三点,再举个例子,应该就明白了。
例子如下:
[code="java"]public class A {
public static void main(String[] args) throws Exception {
String str = "中";
System.out.println(str.getBytes("UTF-8").length);
System.out.println(str.getBytes("GBK").length);
String str1 = new String(str.getBytes("UTF-8"), "GBK");
System.out.println(str1);
System.out.println("=====================");
System.out.println(str1.getBytes("UTF-8").length);
System.out.println(str1.getBytes("GBK").length);
String str2 = new String(str1.getBytes("GBK"), "UTF-8");
System.out.println(str2);
System.out.println("**********************");
String s = "中国";
System.out.println(s.getBytes("UTF-8").length);
System.out.println(s.getBytes("GBK").length);
String str3 = new String(s.getBytes("UTF-8"), "GBK");
System.out.println(str3);
System.out.println("=====================");
System.out.println(str3.getBytes("UTF-8").length);
System.out.println(str3.getBytes("GBK").length);
String str4 = new String(str3.getBytes("GBK"), "UTF-8");
System.out.println(str4);
}
}[/code]
输出结果:
3
2
6
3
??
6
4
9
6
中国
通过结果,应该可以发现,如果有奇数个汉字的时候,编码在解码之后,就会乱码,而对于偶数个汉字没有问题。