Java String 乱码

Java String 乱码问题

今天在工作的时候,本地能正常work的的代码,推到预发环境却出现了部分数据乱码。一开始是怀疑提供这些数据后端服务用错了编码方式,但是本地能work直接否定了这种怀疑。问题出在预发和本地环境的系统编码方式不一致,本地系统默认是UTF-8,而预发默认是GBK编码,因此导致预发环境出现乱码。

new String(byte[] bytes)

如果不指定编码方式,则默认以系统的编码方式。


  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")//查看系统默认编码方式

因此在使用String的时候,无论 encode 或者 decode都要指定编码方式,否则就和系统环境耦合了。

原文地址:https://www.cnblogs.com/Spground/p/9567865.html