繁体   English   中英

如何将字节存储在数组中并获取字符串

[英]how to store byte in an array and get back the string

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

是否可以再次使用此代码工作。 在我的程序中解码回java字符串。 我需要字节数组,所以如何将这个值存储在字节数组中。 我想要类似的程序,但我没有原始文本,而我只有字节数组,那么我该如何获取字符串结果。

您可以使用如下形式:

    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

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

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

要将字符串转换为字节数组,请尝试以下操作

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

您可以使用Base64编码。 这种编码更适合于将二进制数据保存到字符串中,并且具有可移植性。

Java中的Base64 API:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM