Problem description:
This situation often occurs in TOMCAT: the string we input is Chinese characters (the default encoding is GBK), but the default encoding of TOMCAT is ISO8859-1 encoding, so there are errors, resulting in garbled characters.
Solution:
Use ISO8859-1 to convert the string obtained from Tomcat into a byte array again, and then use GBK to encode it.
package cn.com; public class Test7 { public static void main(String[] args) throws Exception { System.out.println("我们输入的汉字,默认编码是gbk"); String str1="大家好"; System.out.println("str1="+str1); byte [] GBKArr=str1.getBytes("gbk"); //等同于 byte [] b1=s1.getBytes();因为它默认的就是gbk编码 System.out.println("Tomcat,默认编码是ISO8859-1编码"); String str2=new String(GBKArr, "iso8859-1"); System.out.println("str2="+str2);//导致乱码 System.out.println("把从Tomcat得到的字符串再次利用ISO8859-1将其变为字节数组,然后利用GBK进行编码"); byte [] ISOArr =str2.getBytes("iso8859-1"); String result=new String(ISOArr,"gbk");//等同于new String(ISOArr);因为默认的就是gbk编码 System.out.println("result="+result); } }
Recommended tutorial:java quick start
The above is the detailed content of Strings in java are always garbled. For more information, please follow other related articles on the PHP Chinese website!