標籤: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 陷阱