如何解决java中字符串出现乱码的问题

这篇文章将为大家详细讲解有关如何解决java中字符串出现乱码的问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

问题描述:

在TOMCAT里经常出现这种情况:我们输入的字符串是汉字(默认的编码是GBK),但是TOMCAT默认的是ISO8859-1编码,于是存在了错误,导致了乱码的产生。

解决办法:

将从Tomcat得到的字符串再次利用ISO8859-1将其变为字节数组,然后利用GBK进行编码。

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);
	}
}

关于解决java中字符串出现乱码的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。