java byte[]转String再转回byte[]不一致问题

最近做项目时,为了将byte[]存入map的value,先将其转为String存入,需要时再取出转回byte[],但实现过程却发现了问题:转回的byte[]与原来不一致:

byte[] bytes = Hex.decode("1a91031001");
String str = new String(bytes);
byte[] after = str.getBytes();
System.out.println("before: " + Hex.encode(bytes) + "--" + Arrays.toString(bytes));
System.out.println("after : " + Hex.encode(after) + "--" + Arrays.toString(after));

输出:

before: 1a91031001--[26, -111, 3, 16, 1]
after : 1a3f031001--[26, 63, 3, 16, 1]

查找资料之后,发现是编码的问题,在我的系统上java默认的编码是GBK:

System.out.println(Charset.defaultCharset().name()); // 输出:GBK

这是多字节编码,也就是需要用多个字节来表示一个字符,所以当字节数组编码成字符串之后,再转回来之后,可能会出现跟原来不一致的问题,解决方法:

指定编码格式为单字节编码,如"ISO-8859-1"

byte[] bytes = Hex.decode("1a91031001");
String str = new String(bytes, Charset.forName("ISO-8859-1"));
byte[] after = str.getBytes(Charset.forName("ISO-8859-1"));
System.out.println("before: " + Hex.encode(bytes) + "--" + Arrays.toString(bytes));
System.out.println("after : " + Hex.encode(after) + "--" + Arrays.toString(after));

输出:

before: 1a91031001--[26, -111, 3, 16, 1]
after : 1a91031001--[26, -111, 3, 16, 1]

参考文章:
https://www.cnblogs.com/Hays4Blog/p/6755550.html
https://blog.csdn.net/wusj3/article/details/80606728

你可能感兴趣的:(java)