Home  >  Article  >  Java  >  java string garbled characters

java string garbled characters

angryTom
angryTomOriginal
2019-11-18 10:22:394167browse

java string garbled characters

java string garbled characters

The problem lies in the inconsistent system encoding methods of pre-release, production and local environments. The system default is UTF-8, while the default encoding for pre-release and production environments is GBK, resulting in garbled characters.

If the encoding method is not specified, the system encoding method will be used by default.

String csn = Charset.defaultCharset().name();
try {
    // use charset name decode() variant which provides caching.
    return decode(csn, ba, off, len);
} catch (UnsupportedEncodingException x) {
    warnUnsupportedCharset(csn);
}
try {
    return decode("ISO-8859-1", ba, off, len);
} catch (UnsupportedEncodingException x) {
    // If this code is hit during VM initialization, MessageUtils is
    // the only way we will be able to get any kind of error message.
    MessageUtils.err("ISO-8859-1 charset not available: " +
        x.toString());
    // If we can not find ISO-8859-1 (a required encoding) then things
    // are seriously wrong with the installation.
    System.exit(1);
    return null;
}
System.getProperty("file.encoding") //查看系统默认编码方式

The solution is as follows:

1. Transcode when using string

System.out.println(str);
String str1 = new String(str.getBytes("ISO-8859-1"), "utf-8");
System.out.println(str1);
String str2 = new String(str.getBytes("gb2312"), "utf-8");
System.out.println(str2);
String str3 = new String(str.getBytes("gbk"), "utf-8");
System.out.println(str3);

2. Transcoding garbled strings

String decodeStr=null;
decodeStr = URLDecoder.decode(url, "utf-8");

Therefore, when using String, the encoding method must be specified regardless of encode or decode, otherwise it will be coupled with the system environment.

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of java string garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:Is java this a pointer?Next article:Is java this a pointer?