如何在数组中存储字节并返回字符串

时间:2013-11-11 06:48:56

标签: java string bytearray

我必须在java中使用字节数组和字符串。我使用java读取文件,并从getBytes()方法获取字节码,即[B @ 1d1cdf7]

使用此代码可以再次使用它吗?在我的程序中解码回来      java字符串。 我需要字节数组,所以如何将这个值存储在字节数组中。我想要某个东西 就像在另一个程序中我没有原始文本,我只有字节 数组然后我怎样才能找回字符串结果。

4 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    while(/* condition */ ) { // Get bytes from the file
        // Append bytes to the byteArray
        stream.write(bytes); 
    }

    String str = new String(stream.toByteArray()); // Get the string representation

答案 1 :(得分:0)

您需要将getBytes()转换为String。

public String toString(){
   return new String(getBytes());
}

答案 2 :(得分:0)

要将字符串转换为字节数组,请尝试此

String test = "This is a test";

byte[] bytes = test.getBytes();
System.out.println("Byte : " + bytes);

现在将字节数组转换为字符串试试这个

String s = new String(bytes);
System.out.println("Text : " + s);

<强>输出

Byte : [B@25154f

Text : This is a test

答案 3 :(得分:-1)

您可以使用Base64编码。这种编码更适合和便携,可以将二进制数据保存到字符串中。

java中的Base64 api:

sun.misc.BASE64Encoder;
sun.misc.BASE64Decoder;