byte[] to file in Java byte[] to file in Java arrays arrays

byte[] to file in Java


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}


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.


Another solution using java.nio.file:

byte[] bytes = ...;Path path = Paths.get("C:\\myfile.pdf");Files.write(path, bytes);