ByteArray to String过程中的编码问题

来源:互联网 发布:mac磁盘怎么看空间 编辑:程序博客网 时间:2024/05/24 05:52

最近因为工作需要,有一个不太常见的需求,中间遇到了一些不太常见的编码的坑,特此记录。因为环境限制,开发语言为Java

需求可以概括为:

  • 发送端将数据序列化后得到的二进制byte数组转为String
  • 接收端接收String后转为byte数组再反序列化为原始数据。

因为发送端是别人开发完成的,我只负责接收端的工作。拿到的String是UTF-8编码的,转为byte数组后反序列化校验失败。

因为序列化使用的是Avro,非常成熟,所以怀疑是编码问题。将String转换后的byte数组依次输出,发现很多-17 -65 -67,基本可以确定了,于是写了个小程序验证了一下。

public class ByteArrayToString {    public static void main(String[] args) throws IOException{        byte[] myByte={115, -110, -1, -2, -3, -4};        System.out.println("-----UTF-8-----");        String utf8Str=new String(myByte, "utf8");        byte[] utf8Byte=utf8Str.getBytes("utf8");        for(byte b:utf8Byte) {            System.out.print(b);            System.out.print(' ');        }        System.out.println();    }}   

程序输出结果为:

-----UTF-8-----115 -17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67

果然UTF-8编码时,一些byte中的信息会丢失。因此在这种转换中不能使用UTF-8编码。那么应该用哪种编码呢?

public class ByteArrayToString {    public static void main(String[] args) throws IOException{        byte[] myByte={115, -110, -1, -2, -3, -4};        System.out.println("-----UTF-8-----");        String utf8Str=new String(myByte, "utf8");        byte[] utf8Byte=utf8Str.getBytes("utf8");        for(byte b:utf8Byte) {            System.out.print(b);            System.out.print(' ');        }        System.out.println();        System.out.println("-----GBK-----");        String gbkStr=new String(myByte, "gbk");        byte[] gbkByte=gbkStr.getBytes("gbk");        for(byte b:gbkByte) {            System.out.print(b);            System.out.print(' ');        }        System.out.println();        System.out.println("-----ISO-8859-1-----");        String isoStr=new String(myByte, "ISO-8859-1");        byte[] isoByte=isoStr.getBytes("ISO-8859-1");        for(byte b:isoByte) {            System.out.print(b);            System.out.print(' ');        }        System.out.println();    }}

输出结果为:

-----UTF-8-----115 -17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67-----GBK-----115 63 -2 -3 63-----ISO-8859-1-----115 -110 -1 -2 -3 -4

发现ISO-8859-1没有问题。原因是ISO-8859-1是单字节编码,所以不存在不能识别的编码。而UTF-8会将不识别的编码标为-17 -65 -67,GBK会将不识别的编码标为63。以后再遇到这种情况就可以很方便的发现编码问题的特征了。

0 0