[轉]Java byte[] 轉 String 陷阱

來源:互聯網
上載者:User

標籤:pre   sse   map   string   span   變化   必須   tput   str   

今天在將byte[] 轉為String,然後再轉回byte[] 時發現一個奇詭的問題。byte[]長度出現了變化。

具體代碼如下:

        Map<String, Persion> map = new HashMap<String, Persion>();        map.put("cn1", new Persion("中國1", 30));        map.put("cn2", new Persion("中國2", 30));        Map<Integer, Map<String, Persion>> classes = new HashMap<Integer, Map<String, Persion>>();        classes.put(1, map);        {            Kryo kryo = new Kryo();            ByteOutputStream stream = new ByteOutputStream();            Output output = new Output(stream);            kryo.writeClassAndObject(output, classes);            output.flush();            byte[] bytes = stream.getBytes();            String str = new String(bytes,"utf-8");            byte[] bytes2 = str.getBytes("utf-8");            System.out.println(bytes.length + "\n" + str.length() + "\n" + bytes2.length);        }

輸出為:

102410161036

經過實驗發現原來是編碼問題:

 

ByteOutputStream 預設的編碼是 "ISO8859-1" 而非 "utf-8".

所以在從Stream擷取byte並轉為String時必須指定為 "ISO8859-1"編碼。

            byte[] bytes = stream.getBytes();            String str = new String(bytes, "ISO8859-1");            byte[] bytes2 = str.getBytes("ISO8859-1");            System.out.println(bytes.length + "\n" + str.length() + "\n" + bytes2.length);<pre name="code" class="java">

此時輸出長度均為1024。

[轉]Java 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.