如何在Java中将字节数组转换为文件?
byte[] objFileBytes, File objFile
如何在Java中将字节数组转换为文件?
byte[] objFileBytes, File objFile
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(yourFile));
bos.write(fileBytes);
bos.flush();
bos.close();
您也可以使用Writer而不是OutputStream。使用Writer将允许您编写文本(String,char [])。
BufferedWriter bw = new BufferedWriter(new FileWriter(yourFile));
既然你说你想把一切都保存在内存中,又不想写什么东西,那么你可以尝试使用ByteArrayInputStream
。这个类模拟了一个输入流,你可以将其传递给大多数类。
ByteArrayInputStream bais = new ByteArrayInputStream(yourBytes);
public void writeToFile(byte[] data, String fileName) throws IOException{
FileOutputStream out = new FileOutputStream(fileName);
out.write(data);
out.close();
}
file
不能在内存中,所以你无法做到你想要的。为什么你还想这样做呢?这没有太多意义。如果你解释一下原因,也许人们可以给出其他建议。 - CanerFileOutputStream fos = new FileOutputStream(objFile);
fos.write(objFileBytes);
fos.close();
好的,你要求了:
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);
请参考如何在Android中呈现PDF。看起来您可能没有其他选择,除了将内容保存到SD文件的(临时)位置,以便能够在pdf查看器中显示它。