在Java中将byte []写入File

时间:2011-07-26 10:28:04

标签: java arrays file file-io

如何在Java中将字节数组转换为File?

byte[] objFileBytes, File objFile

5 个答案:

答案 0 :(得分:79)

文件对象不包含文件的内容。它只是指向硬盘驱动器(或其他存储介质,如SSD,USB驱动器,网络共享)上的文件的指针。所以我认为你想要的是把它写到硬盘上。

您必须使用Java API中的某些类来编写文件

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(yourFile));
bos.write(fileBytes);
bos.flush();
bos.close();

您也可以使用Writer而不是OutputStream。使用编写器将允许您编写文本(String,char [])。

BufferedWriter bw = new BufferedWriter(new FileWriter(yourFile));

由于您说您希望将所有内容保留在内存中并且不想编写任何内容,因此您可能会尝试使用ByteArrayInputStream。这模拟了一个InputStream,您可以将其传递给大多数类。

ByteArrayInputStream bais = new ByteArrayInputStream(yourBytes);

答案 1 :(得分:24)

public void writeToFile(byte[] data, String fileName) throws IOException{
  FileOutputStream out = new FileOutputStream(fileName);
  out.write(data);
  out.close();
}

答案 2 :(得分:5)

使用FileOutputStream。

FileOutputStream fos = new FileOutputStream(objFile);
fos.write(objFileBytes);
fos.close();

答案 3 :(得分:4)

好的,你要求它:

File file = new File("myfile.txt");

// convert File to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytes = bos.toByteArray();

// convert byte[] to File
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
File fileFromBytes = (File) ois.readObject();
bis.close();
ois.close();

System.out.println(fileFromBytes);

但这毫无意义。请说明您要实现的目标。

答案 4 :(得分:1)

How to render PDF in Android。看起来您可能没有任何选项,除了将内容保存到SD文件上的(临时)以便能够在pdf查看器中显示它。

相关问题