Home> Java> JavaBase> body text

Strings in java are always garbled

王林
Release: 2019-11-23 11:25:32
Original
3231 people have browsed it

Strings in java are always garbled

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); } }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!