Java-String-數據亂碼


    /**
     * 前后端數據亂碼問題
     * 解決辦法1:
     * 亂碼原因:一編一解碼型不一致導致。
     * [main description]
     * @param  {[type]} String[] args          [description]
     * @return {[type]}          [description]
     */
    public static void main(String[] args) {
        String name = "您好,中國!";                            
        String striso8859,strgb2312,strgbk,strutf16,strutf8 = "";
        byte[] iso8859,gb2312,gbk,utf16,utf8;
        try {
            /** 
             * String.getBytes("");
             *     String:當前亂碼的數據字符串。
             *  String.getBytes(String str):將亂碼的數據字符串轉換為byte數組。
             *  String.getBytes(String str)中的參數str是當前編碼類型。(這個類型是當前亂碼的類型)
             */
            iso8859 = name.getBytes("ISO-8859-1");      
            gb2312 = name.getBytes("GB2312");           
            gbk = name.getBytes("GBK");                 
            utf16 = name.getBytes("UTF-16");            
            utf8 = name.getBytes("UTF-8");
            
            /**
             * String(Byte [] byte,String str)
             * String提供將不同編碼格式的byte數組轉化為字符串數據的構造函數,其中:
             * byte是轉換后的亂碼byte數組,String類型的str則是聲明即將要轉換成為編碼格式。
             */
            striso8859 = new String(iso8859,"UTF-8");
            strgb2312 = new String(gb2312,"UTF-8");
            strgbk = new String(gbk,"UTF-8");
            strutf16 = new String(utf16,"UTF-8");
            strutf8 = new String(utf8,"UTF-8");
            System.out.println(striso8859);
            System.out.println(strgb2312);
            System.out.println(strgbk);
            System.out.println(strutf16);
            System.out.println(strutf8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }              
    }
    
 /**
     * 前后端數據亂碼問題
     * 解決辦法2:
     * 亂碼原因:一編一解碼型不一致導致。
     */

HttpServletRequest.setCharacterEncoding("utf-8");
HttpServletResponse.setCharacterEncoding("utf-8");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM