String str="中国";

String str1=new String(str.getBytes("gbk"),"ISO8859_1");String str2=new String(str1.getBytes("ISO8859_1"),"gbk");
System.out.println("Received: " + str2);   // 这一行能够输出"中国" 问题1 为什么下面第二行改成utf-8,就不能正确输出?String str="中国";

String str1=new String(str.getBytes("utf-8"),"ISO8859_1");  //改成了utf-8String str2=new String(str1.getBytes("ISO8859_1"),"gbk");
System.out.println("Received: " + str2);   // 这一行输出乱码
问题2 问题1 为什么都改成了utf-8还是不能正常String str="中国";

String str1=new String(str.getBytes("utf-8"),"ISO8859_1");  //改成了utf-8String str2=new String(str1.getBytes("utf-8"),"gbk"); // 也改成了utf-8
System.out.println("Received: " + str2);   // 这一行输出乱码
难道string.getBytes(string charset) 的charset不是任意选择的?

解决方案 »

  1.   

    String str="中国";String str1=new String(str.getBytes("gbk"),"utf-8");
    System.out.println("Received: " + str1);String str2=new String(str1.getBytes("utf-8"),"gbk");
    System.out.println("Received: " + str2);    
    这个为什么也不行啊,我把gbk转成utf-8的,然后又从utf-8转成gbk的,也有错误?
      

  2.   

    String str2=new String(str1.getBytes("utf-8"),"gbk"); // 也改成了utf-8
    -------------------------------------
    把gbk改成了utf-8,但原来不是gbk
      

  3.   

    把gbk改成了utf-8,但原来不是gbk
    ==========================
    原来不是utf-8是什么意思?你的意思是 string.getbyte("utf-8"),这句话正确的前提是string必须是utf-8编码的?
      

  4.   

    这是因为原编码和转换用的编码不兼容,这一转换过程完成后不可逆,即以错误编码得到的字符无法还原成正确的编码.
    Note:1.utf-8采用2/3混编的方式。目前容纳的汉字范围小于gbk编码。
         2.按照GBK18030、GBK、GB2312的顺序,3种编码是向下兼容.
         3.utf-8只兼容iso-8859-1,对于其他编码方式并不兼容.
      

  5.   

    多谢,楼上,有点明白了。既然utf-8容纳汉字的范围小,那为什么浏览器会可以默认用utf-8编码给webserver发送数据?如果碰到不能编码的汉字,不就出错了?
      

  6.   

    utf-8跟gbk不兼容,utf-8只兼容iso-8859-1,对于其他编码方式并不兼容.好像很少有人提到?
      

  7.   

    utf-8只兼容iso-8859-1,对于其他编码方式并不兼容.很多文章提到utf编码兼容很
    多其他编码的提法其实只是表明,其他编码中的字符在utf-8中有对应的字符,但他们的位置
    并不相同.而且存在其他编码有的字utf没有的情况.如gbk.
      

  8.   

    是他本来设计的问题.在新的api中getBytes()已经过时了.
      

  9.   

    是他本来设计的问题.在新的api中getBytes()已经过时了.
    ======================
    果然不出我所料,我感觉不带参数的getBytes()对程序员的陷害太大了。请问,新的API中是怎么修改的?
      

  10.   

    可能我说过时有点不合适,但是,在byte转换成string确实是有些漏洞.但是,你的代码有意的避开
    ISO-8859-1看来你对为什么会这样是是了解的.ISO-8859-1是唯一一个能让顺序打印的字符.其它的为什么不行因为字符的转换模式之间存在很大的区别.
    public class Uceshi {
     public static void main(String[] args) throws java.io.UnsupportedEncodingException{    String str="中国";
        String str1=new String(str.getBytes("utf-8"),"ISO8859_1");
        String str2=new String(str1.getBytes("ISO8859_1"),"utf-8");
        System.out.println("Received: " + str2);  }}一样能打印"中国".换成"gbk"也是一样的.