Java – Convert byte[] to File
This tutorial shows several ways to convert a byte[] array to File in Java.
1- Traditional way
The traditional way of doing the conversion is through using FileOutputStream as the following:
1 2 3 4 5 6 7 8 9 10 11 12 | public static File convertUsingOutputStream(byte[] fileBytes) { File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf"); try (FileOutputStream fos = new FileOutputStream(f)) { fos.write(fileBytes); } catch(Exception ex) { ex.printStackTrace(); } return f; } |
2- Java NIO
With Java 7, you can do the conversion using Files utility class of nio package:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static File convertUsingJavaNIO(byte[] fileBytes) { File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf"); try { Files.write(f.toPath(), fileBytes); } catch (Exception ex) { ex.printStackTrace(); } return f; } |
3- Apache Commons IO
Besides JDK, you can do the conversion using Apache Common IO library as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static File convertUsingCommonsIO(byte[] fileBytes) { File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf"); try { FileUtils.writeByteArrayToFile(f, fileBytes); } catch(Exception ex) { ex.printStackTrace(); } return f; } |