您的位置 首页 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快速入门

文章来源:智云一二三科技

文章标题:java中的字符串总是出现乱码

文章地址:https://www.zhihuclub.com/16273.shtml

关于作者: 智云科技

热门文章

网站地图