如何避免字符串乱码呢?
下文笔者讲述字符串实例化时乱码的处理方法,如下所示
实现思路: 使用new String实例化时 指定相应的编码方式,即可避免字符串乱码现象例
package com.java265; //字符串乱码问题的解决 //问题说明: //在TOMCAT中当输入字符串是汉字(默认的编码是GBK) //但TOMCAT默认是ISO8859-1编码,此时就会出现错误,导致乱码现象发生 //解决办法 //将从Tomcat得到的字符串再次利用ISO8859-1将其变为字节数组 //然后使用GBK进行编码 public class TestClass { 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); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。