首页 > 编程语言 > 详细

[转]Java byte[] 转 String 陷阱

时间:2017-10-09 20:28:23      阅读:255      评论:0      收藏:0      [点我收藏+]

今天在将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。

[转]Java byte[] 转 String 陷阱

原文:http://www.cnblogs.com/sunshineyy/p/7642726.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!