iteye_9874 2009-08-21 00:55
浏览 255
已采纳

问一个java字符编码的问题

情况如下:

String str = "中";
String newStr = new String(str.getBytes("GBK"), "UTF-8");

newStr还能还原成str吗?感觉是不能了。

 

  • 写回答

5条回答 默认 最新

  • walsh_bupt 2009-08-21 02:14
    关注

    [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
    中国

    通过结果,应该可以发现,如果有奇数个汉字的时候,编码在解码之后,就会乱码,而对于偶数个汉字没有问题。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型