首页 > 解决方案 > Java:将字节字符串转换为字节数组

问题描述

我想将 my 转换byte[]为 a String,然后将其转换String为 a byte[]

所以,

byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);

bstring 给我[B@74e752bb

然后转换Stringbyte[]. 我没有按此顺序使用它,但这是一个示例。

我需要如何在 Java 中执行此操作?

标签: javaarraysbyte

解决方案


将 byte[] 转换为 String 时,应该使用这个,

new String(b, "UTF-8");

代替,

b.toString();

将字节数组转换为字符串时,应始终指定字符编码并在从字符串转换回字节数组时使用相同的编码。最好是使用 UTF-8 编码,因为它非常强大且紧凑,可以表示超过一百万个字符。如果您不指定字符编码,则可能会使用平台的默认编码,当从字节数组转换为字符串时,可能无法正确表示所有字符。

如果处理得当,你的方法应该写成这样,

    public static void main(String args[]) throws Exception {
        byte[] b = myFunction();
//      String bstring = b.toString(); // don't do this
        String bstring = new String(b, "UTF-8");
        byte[] ser = bstring.getBytes("UTF-8");
        /* Here the methode to convert the bstring to byte[], and call it ser */
        String deser = new String(ser, "UTF-8");
    }

推荐阅读