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

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


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讲师

répondre à tous(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 为 "�Ϻ��Ϻ�"
另外字节数组为:

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!