zoukankan      html  css  js  c++  java
  • 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都要指定编码方式,否则就和系统环境耦合了。

  • 相关阅读:
    LeetCode:Remove Nth Node From End of List
    LeetCode:Swap Nodes in Pairs
    LeetCode:Merge Two Sorted Lists
    LeetCode:Maximum Subarray
    LeetCode:Linked List Cycle
    LeetCode:Search Insert Position
    LeetCode:Roman to Integer
    算法程序设计题语言类笔记
    我的小游戏之2048
    LeetCode:Best Time to Buy and Sell Stock II
  • 原文地址:https://www.cnblogs.com/Spground/p/9567865.html
Copyright © 2011-2022 走看看