java 字串編碼轉換

來源:互聯網
上載者:User

/本程式預設在UTF8編碼下運行
        String a = "鄭高強";
        String b = null;
        b = new String(a.getBytes(),"UTF8");
        System.out.println(b);  //正確顯示
        b = new String(a.getBytes("GB2312"),"GB2312");
        System.out.println(b);  //正確顯示。雖然a本來預設是三位元組編碼的,但getBytes("GB2312")
                                //把整個位元組數組按雙位元組形式轉換了一次。用GB2312來解釋這個新位元組數組就對了
        b = new String(a.getBytes("GB2312"),"UTF8");
        System.out.println(b);  //亂碼。已經轉為雙位元組,還用UTF8解釋就錯了。
                                //還沒想到怎麼把b救回來。好像沒辦法使得b重新正確顯示了。
        
        b = new String(a.getBytes(),"GB2312");
        System.out.println(b);  //亂碼。getBytes已經把字串逐個字元按UTF8格式,拆散為N個位元組。
                                //後邊硬用GB2312來解釋這N個位元組,肯定亂碼。UTF8三位元組,GB2312雙位元組
        b = new String(a.getBytes("UTF8"),"GB2312");    //同上一句其實一樣

        System.out.println(b);  //亂碼

 

結果:

鄭高強

鄭高強

֣��ǿ

���寮�

���寮�

 

字元編碼轉換關鍵是要理解內在的機理。。。編碼的關鍵是要理解最底層那個位元組數組是怎麼編碼的,例如GB2312用兩個位元組表示一個漢字,UTF8用三個位元組表示一個漢字,可見,底層的位元組數組肯定有不同~~~

 

!!!Java要轉換字元編碼:就一個String.getBytes("charsetName")解決,這時候已經把原來String的位元組數組逐個字元的轉化了,此時編碼已經變了。例如原來是UTF8三位元組編碼,轉為GB2312,已經變成雙位元組編碼了,這個byte數組已經比原來String內含的數組要短。

而new String只是一個組裝String的過程,傳入的位元組數組是什麼編碼的,就該用什麼編碼組裝(或者叫解釋),不然就悲劇了~~~

 

!!!雖然程式預設編碼是UTF8,這不代表程式中用GB2312編碼的字串就無法正確顯示。(這是我個人之前的誤解)因為out.println的時候,系統會自動處理。其實預設編碼是UTF8,就只是指getBytes或者new
InputStreamReader這樣的操作的時候,預設用UTF8來解釋。


 

再說說編碼和字元集的關係:詳細見另外一個文章http://www.cnblogs.com/kenkofox/archive/2010/10/15/1851962.html 

 

最後貼出JDK對String的getBytes和new String(byte[], charsetName)的解釋:

public byte[] getBytes()

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

 

new String(byte[], charsetName)

Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.