utf-8 - java utf8 转 gb2312 错误?
PHP中文网
PHP中文网 2017-04-17 15:34:05
0
3
665

直接上代码,方便同学可以复制下来跑跑


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

跪请大神赐教啊!!!!

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(3)
阿神

Java 所有的String 都是Unicode 編碼的,使用String.getBytes(...) 得到的就是對於編碼的位元組數組,你這段程式碼效果是把UTF8 編碼的位元組數組直接讀成GB2312 的,當然是不對的。
String 本身就是統一的編碼了,如果需要輸出特定編碼的字串,直接使用 String.getBytes(...) 就能獲得對應編碼的字串位元組數組,不存在轉換這個概念。

如果是把 UTF8 形式的字串位元組數組,轉成 GB2312 形式的,程式碼應該是

byte[] bytes = ...
String str = new String(bytes, "UTF-8");
bytes = str.getBytes("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) 這一步就可以了。該位元組數組需要用編碼時相同的編碼格式進行解碼。否則會亂碼。如果,這時候用已經亂碼的字串再轉換編碼,是不一定能得到之前正確的編碼位元組數組的。

範例:

String str = "上海上海"; // 我这设置 file.encoding 为 UTF-8
        byte[] utf8Bytes = str.getBytes("utf-8");
        byte[] defaultBytes = str.getBytes();
        Assert.assertArrayEquals(utf8Bytes, defaultBytes);

        byte[] gbkBytes = str.getBytes("GBK");
//        Assert.assertArrayEquals(utf8Bytes, gbkBytes);// 这儿不过!! array lengths differed, expected.length=12 actual.length=8。

        String errorStr = new String(gbkBytes, "utf-8");// 此时是乱码的
        Assert.assertNotEquals(str, errorStr); // 肯定不一样
        byte[] errorUtf8Bytes = errorStr.getBytes("utf-8"); // 乱码后重新编码
//        Assert.assertArrayEquals(gbkBytes, errorUtf8Bytes); // 不过! 已经和之前的字节数组不一样了。array lengths differed, expected.length=8 actual.length=16
//        Assert.assertArrayEquals(utf8Bytes, errorUtf8Bytes); // 不过! 更不会和 utf8Bytes 相同。array lengths differed, expected.length=12 actual.length=16

其中:errorStr 為 "�Ϻ��Ϻ�"
另外位元組數組為:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!