Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte[] to file in Java

With Java:

I have a byte[] that represents a file.

How do I write this to a file (ie. C:\myfile.pdf)

I know it's done with InputStream, but I can't seem to work it out.

like image 465
elcool Avatar asked Dec 03 '10 21:12

elcool


3 Answers

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
like image 61
bmargulies Avatar answered Nov 20 '22 21:11

bmargulies


Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

like image 45
SharkAlley Avatar answered Nov 20 '22 23:11

SharkAlley


Another solution using java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
like image 153
TBieniek Avatar answered Nov 20 '22 23:11

TBieniek