Write byte[] to File in Java [closed]

2019-01-17 06:41发布

How to convert byte array to File in Java?

byte[] objFileBytes, File objFile

5条回答
手持菜刀,她持情操
2楼-- · 2019-01-17 07:08

See How to render PDF in Android. It looks like you may not have any option except saving the content to a (temporary) on the SD file in order to be able to display it in the pdf viewer.

查看更多
欢心
3楼-- · 2019-01-17 07:13
public void writeToFile(byte[] data, String fileName) throws IOException{
  FileOutputStream out = new FileOutputStream(fileName);
  out.write(data);
  out.close();
}
查看更多
Fickle 薄情
4楼-- · 2019-01-17 07:21

A File object doesn't contain the content of the file. It is only a pointer to the file on your hard drive (or other storage medium, like an SSD, USB drive, network share). So I think what you want is writing it to the hard drive.

You have to write the file using some classes in the Java API

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

You can also use a Writer instead of an OutputStream. Using a writer will allow you to write text (String, char[]).

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

Since you said you wanted to keep everything in memory and don't want to write anything, you might try to use ByteArrayInputStream. This simulates an InputStream, which you can pass to the most of the classes.

ByteArrayInputStream bais = new ByteArrayInputStream(yourBytes);
查看更多
时光不老,我们不散
5楼-- · 2019-01-17 07:22

Use a FileOutputStream.

FileOutputStream fos = new FileOutputStream(objFile);
fos.write(objFileBytes);
fos.close();
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-17 07:35

Ok, you asked for it:

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);

But this is pointless. Please specify what you are trying to achieve.

查看更多
登录 后发表回答