[Java]_[初級]_[utf8編碼的byte[]數群組轉換為String時要注意的問題]

來源:互聯網
上載者:User

標籤:java   string   byte   轉換   utf-8   


情境:

1. 通過socket給Java傳遞byte[]數組時,utf-8的位元組數組在轉換為String, Java並不會遇到0就停止結束,而是一直使用完byte[]的容量,

所以在轉換為Java的String需要自己判斷位元組值是0的位置,再截取數組長度。


public  static int searchByte(byte[] data, byte value) {int size = data.length;for (int i = 0; i < size; ++i) {if (data[i] == value) {return i;}}return -1;}public static void main(String[] args) {byte[] info = new byte[10];info[0] = 0x31;info[1] = 0x31;info[2] = 0;info[3] = 0x1;info[4] = 0x32;info[5] = 0;try {String utf8 = new String(info, "UTF-8");// 1.這裡時數組的大小,而不是2,String即使遇到0也會繼續載入到String裡.// 輸出: 10System.out.println("" + utf8.length());// 1.輸出很奇怪,不會輸出不可見字元的預留位置// 輸出: 112System.out.println(utf8);if (utf8.equalsIgnoreCase("112")) {// 和112不等,這裡不會輸出.System.out.println("It is same with 112");}byte[] info1 = utf8.getBytes("UTF-8");// 1. 還原為byte[],探索資料並沒有丟失.// 輸出: 10:0:1:50System.out.println("info1: " + info1.length + ":" + info1[2] + ":"+ info1[3] + ":" + info1[4]);// 1. 所以如果需要到0結束的utf8位元組數組,需要自己判斷0並截取.int offset = -1;// binarySearch 必須要數組升序排序了才可以用,所以不能用.// offset = Arrays.binarySearch(info, (byte)0);offset = searchByte(info,(byte)0);String info2 = new String(info, 0, offset, "UTF-8");// 輸出: 11System.out.println("info2: " + info2);// 輸出: 2System.out.println("" + info2.length());} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}


[Java]_[初級]_[utf8編碼的byte[]數群組轉換為String時要注意的問題]

聯繫我們

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