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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值