Java byte[]字节数组转换为String字符串的注意事项

来源:互联网 发布:淘宝大股东是日本谁 编辑:程序博客网 时间:2024/04/30 07:47

Java byte[]字节数组转换为String字符串的注意事项

一、toString()

开始我想当然的使用toString()方法进行转换,结果如下:

[B@1b67f74

乍一看就是“乱码”。其实这是hashcode编码,JDK源码如下:

    public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

二、new String()

String target = new String(byte[] 字节数组对象)

JDK源码:

    public String(byte bytes[]) {
    this(bytes, 0, bytes.length);
    }

    public String(byte bytes[], int offset, int length) {
    checkBounds(bytes, offset, length);
    char[] v  = StringCoding.decode(bytes, offset, length);
    this.offset = 0;
    this.count = v.length;
    this.value = v;
    }
综上:

对于byte[]字节数组采用toString()方法是行不通的。

正确的方法是使用byte[]数组做参数,新建一个String对象。


0 0