Java中getBytes()的用法__Java

來源:互聯網
上載者:User
package com.test.bs;/** *  * 1、Unicode是一種編碼規範,是為解決全球字元通用編碼而設計的,而rUTF-8,UTF-16等是這種規範的一種實現。   2、java內部採用Unicode編碼規範,也就是支援多語言的,具體採用的UTF-16編碼方式。   3、不管程式過程中用到了gbk,iso8859-1等格式,在儲存與傳遞的過程中實際傳遞的都是Unicode編碼的資料,要想接收到的值不出現亂碼,就要保證傳過去的時候用的是A編碼,接收的時候也用A編碼來轉換接收。   4、如果雙方的file.encoding確保都相同,那就省事了,都預設轉了,但往往在不同項目互動時很多時候是不一致的,這個時候是必須要進行編碼轉換的。   5、無論如論轉換,java程式的資料都是要先和Unicode做轉換,這樣也就是能處理多語言字元集的原因了。底層保持了一致,只要在傳值和接值的時候也一致就肯定不會出現亂碼了。 * */public class UnicodeTest1 {public static void main(String args[]) throws Exception {String str = "中文字元";System.out.println("original string---" + str);// 會正常輸出原始串/** *  * str.getBytes();如果括弧中不寫charset,則採用的是Sytem.getProperty("file.encoding"),即當前檔案的編碼方式, *  * 很多人寫的是系統的預設編碼,通過代碼測試並非如此,實際得到的是檔案的編碼方式* *  * str.getBytes("charset");//指定charset,即將底層儲存的Unicode碼解析為charset編碼格式的位元組數組方式 *  * String new_str=new String(str.getBytes("utf-8"),"gbk")); *  * //將已經解析出來的位元組資料轉化為gbk編碼格式的字串,在記憶體中即為gbk格式的位元組數組轉為Unicode去互動傳遞 */String new_str = new String(str.getBytes("utf-8"), "gbk");/** *  * 此時的輸出是亂碼,在UTF-8的file.encoding下輸出gbk格式的資料肯定是亂碼,但是new_str的確是gbk編碼式的 *  * 此時的亂碼源於encoding不符,但gbk格式的new_str本身資料並沒有問題,通過下面的轉換也可以看得出來 */System.out.println("new string----" + new_str);String final_str = new String(new_str.getBytes("gbk"), "utf-8");// 此處的含意與最上邊的注釋是一致的參數含意/** *  *輸出是正常的,此時將gbk編碼格式的new_str字串,用gbk這個charset去解析它,然後用utf-8再轉碼一次, *  * 因為new_str確實是gbk格式的,才能經過utf-8編碼得到正常的資料顯示。 */System.out.println("final string---" + final_str);}}


 

 

package com.test.bs;import java.io.UnsupportedEncodingException;public class UnicodeTest2 {public static void main(String[] args) {String a = "哈哈";try {byte[] gb2312 = a.getBytes("GB2312");byte[] utf = a.getBytes("UTF-8");for (int i = 0; i < gb2312.length; i++) {System.out.print(gb2312[i]);}System.out.println();for (int i = 0; i < utf.length; i++) {System.out.print(utf[i]);}System.out.println();System.out.println(new String(gb2312));System.out.println(new String(utf));System.out.println(System.getProperty("file.encoding"));//當前檔案的編碼方式System.out.println(new String(utf, "UTF-8"));System.out.println(new String(gb2312, "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}}}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.