在Java中将byte 写入文件
如何在Java中将字节数组转换为File?
byte[] objFileBytes, File objFile
File对象不包含文件的内容。 它只是指向硬盘驱动器(或其他存储介质,如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);
public void writeToFile(byte[] data, String fileName) throws IOException{ FileOutputStream out = new FileOutputStream(fileName); out.write(data); out.close(); }
使用FileOutputStream。
FileOutputStream 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查看器中显示它。