直接上代码,方便同学可以复制下来跑跑
try {
String str = "上海上海";
String gb2312 = new String(str.getBytes("utf-8"), "gb2312");
String utf8 = new String(gb2312.getBytes("gb2312"), "utf-8");
System.out.println(str.equals(utf8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
结果打印false
jdk7和8下面都是这结果,ide编码是utf-8
跪请大神赐教啊!!!!
Java 所有的String 都是Unicode 編碼的,使用String.getBytes(...) 得到的就是對於編碼的位元組數組,你這段程式碼效果是把UTF8 編碼的位元組數組直接讀成GB2312 的,當然是不對的。
String 本身就是統一的編碼了,如果需要輸出特定編碼的字串,直接使用 String.getBytes(...) 就能獲得對應編碼的字串位元組數組,不存在轉換這個概念。
如果是把 UTF8 形式的字串位元組數組,轉成 GB2312 形式的,程式碼應該是
字串gb2312和utf8都已經是亂碼了,new String(str.getBytes("utf-8"), "gb2312")意思是使用utf-8來編碼,再使用gb2312解碼,肯定亂碼
題主應該是對編解碼有誤解。
getBytes(String charsetName) 是指用 chasetName 代表的編碼格式對字串進行編碼得到位元組數組。
String(byte bytes[], String charsetName) 建構方法是指用 chasetName 代表的編碼格式 對直接陣列進行解碼得到字串。
也就是說,得到以某種格式編碼的字元陣列只用 getBytes(String charsetName) 這一步就可以了。該位元組數組需要用編碼時相同的編碼格式進行解碼。否則會亂碼。如果,這時候用已經亂碼的字串再轉換編碼,是不一定能得到之前正確的編碼位元組數組的。
範例:
其中:errorStr 為 "�Ϻ��Ϻ�"
另外位元組數組為: