byte to string java_Java byte[] 转 String 陷阱

今天在将byte[] 转为String,然后再转回byte[] 时发现一个奇诡的问题。byte[]长度出现了变化。

具体代码如下:

Map map = new HashMap();

map.put("cn1", new Persion("中国1", 30));

map.put("cn2", new Persion("中国2", 30));

Map> classes = new HashMap>();

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);

此时输出长度均为1024。


版权声明:本文为weixin_35480412原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。