String str = "你好吗";
System.out.println(str);
String str1 = new String(str.getBytes("utf8"));
System.out.println(str1); str1 = new String(str1.getBytes("GBK"));
System.out.println(str1);你好吗
浣犲ソ鍚
娴g姴銈介崥锟�疑问:汉字转成了UTF8,怎么转不回来了啊??
另外我是要把中文STRING转成UTF8然后发给PYTHON.
用JAVA把中文"你好吗"转成UTF8是:浣犲ソ鍚
变成十六进制是:\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90
用PYTHON把中文"你好吗"转成UTF8是:'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97'
为什么会不一样呢?好奇怪.请朋友和前辈们帮看一下啊.快崩溃了..

解决方案 »

  1.   

    JAVA里都是UNICODE编码。
    UTF-8 每个汉字是3个字节,你转的少了一个,是你代码的问题。看我的代码
      public static void main(String args[]) throws UnsupportedEncodingException {
        String str = "你好吗";
        System.out.println(str);
        byte[] bs = str.getBytes("utf-8");
        System.out.println(bs.length);
        String str1 = new String(bs);
        System.out.println(str1);
        str1 = new String(str1.getBytes(),"utf-8");
        System.out.println(str1);
        str1 = new String(bs,"utf-8");
        System.out.println(str1);
      }三个汉字转为byte是9个,你又非得重新组合成unicode的字符串,2个算1个,等于4个字符,无形中丢了一个啦!
      

  2.   

    你把
    String str = "你好吗吗";
    双数的字符,看得就更清楚了。 真凑巧,双数转化后为12个字节,拼成了6个字符。你再转回去依然是对的。哈哈! 不过可不能这么干哦!
      

  3.   

    不一样是因为平台的默认charset不同吧String str1 = new String(str.getBytes("utf8"));
    使用的是平台默认的charset来解码String str1 = new String(str1.getBytes("utf8"),"utf-8");
    手工指定解码方式汉字就不乱码了
            
      

  4.   

    问题在于,你千万不要把byte[] 再转化为String 啦!直接用byte[] 发送不就行了。如果嫌麻烦,把byte[]Base64编码后,以字符串的方式发过去也行。另外,这段代码也许你用得着
      public static String byteToString(byte[] bs) {
        byte high, low;
        byte maskHigh = (byte) 0xf0;
        byte maskLow = 0x0f;
        StringBuffer buf = new StringBuffer();
        for (byte b : bs) {
          high = (byte) ((b & maskHigh) >> 4);
          low = (byte) (b & maskLow);
          buf.append(findHex(high));
          buf.append(findHex(low));
        }
        return buf.toString();
      }