Write byte array to file

This java example will demonstrate writing a byte array to a file using java, google guava, apache commons. When each test is run it will write 'fileAsByteArray' which represents 'File to byte array' string to the OUTPUT_FILE_NAME.


private byte[] fileAsByteArray = {
            70, 105, 108, 101, 32,
            116, 111, 32, 98, 121,
            116, 101, 32, 97, 114,
            114, 97, 121};

private static final String OUTPUT_FILE_NAME = "output/ByteArrayToFile.txt";

Straight up Java

Using a java solution that would work with java 1.4 and above, we will write a byte array to a file using FileOutputStream by passing in the byte array to its constructor. Next calling the writes method will write the length of the bytes from the specified array to the file output stream.


public void convert_byte_array_to_file_java () throws IOException {

    FileOutputStream fos = new FileOutputStream(OUTPUT_FILE_NAME);

Java 7 File I/O

Using Files, a java utility class introduced in java 7, write byte array into file by calling the write passing in the Path where the file should we written to the array. There is a 3rd parameter not shown below which allows you to specify options on how the file is created. For instance, if you want to truncate and existing file you can pass in StandardOpenOption.TRUNCATE_EXISTING

public void convert_byte_array_to_file_java_nio () throws URISyntaxException, IOException {

    Path path = Paths.get(OUTPUT_FILE_NAME);

    java.nio.file.Files.write(path, fileAsByteArray);

Google Guava

This snippet will show how to write the content of a byte array to a file using guava Files utility class.

public void convert_byte_array_to_file_guava () throws IOException {

    File fileToWriteTo = new File(OUTPUT_FILE_NAME);

    Files.write(fileAsByteArray, fileToWriteTo);

Apache Commons

Apache commons has a similar method above for writing a byte array to a file.

public void convert_byte_array_to_file_apache_ioutils () throws IOException {

    File fileToWriteTo = new File(OUTPUT_FILE_NAME);

    FileUtils.writeByteArrayToFile(fileToWriteTo, fileAsByteArray);