Java byte[] 转 String 陷阱

今天在将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);
        }

输出为:

1024
1016
1036

经过试验发现原来是编码问题:

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。 
 


你可能感兴趣的:(String,byte)