我已经将一个字节数组byte[] testByte; testByte = new byte[]{3,4}存储到了一个文件中,现在我需要从文件中读取并将字节数组分配给一个变量并打印出来。
我已经完成了以下代码,但无法打印字节数组
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
try{
// create input stream from file input stream
is = new FileInputStream("c:\\test.txt");
// create data input stream
dis = new DataInputStream(is);
// count the available bytes form the input stream
int count = is.available();
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);
}现在,如何将缓冲区bs中的内容存储到数组中。
请帮我解决这个问题
发布于 2014-11-06 16:56:11
可以使用bs存储new String缓冲区的内容。
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
int count = 0;
byte[] bs = null;
String content = "";
try{
is = new FileInputStream("C:\\test.txt");
dis = new DataInputStream(is);
count = is.available();
bs = new byte[count];
dis.read(bs);
// here is a variable that contains the buffer content as a String
content = new String(bs);
} catch (IOException e) {
} finally {
is.close();
dis.close();
}
System.out.println(content);
}编辑(回复注释):当我们创建new String()时,我们用byte[]值实例化一个新字符串。但是,由于您已经有了一个字节数组,所以您可以使用以下方法再次将String对象的值存储在上面:
bs = content.getBytes();预先,如果字节的打印是不同的,比如[B@199c55a [B@ same 824--它只是给对象的名称,但两者的值是相同的),请不要担心。
https://stackoverflow.com/questions/26781005
复制相似问题