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
}
Answer from bmargulies on Stack Overflow
🌐
How to do in Java
howtodoinjava.com › home › i/o › writing byte[] to a file in java
Writing Byte[] to a File in Java
April 18, 2022 - Do not forget to close the output ... FileOutputStream(file)) { os.write(bytes); } The FileUtils class has method writeByteArrayToFile() that writes the byte array data into the specified file....
🌐
Baeldung
baeldung.com › home › java › java io › writing byte[] to a file in java
Writing byte[] to a File in Java | Baeldung
May 13, 2026 - We’ll open an output stream to our destination file, and then we can simply pass our byte[] dataForWriting to the write method. Note that we’re using a try-with-resources block here to ensure that we close the OutputStream in case an IOException is thrown. The Java NIO package was introduced in Java 1.4, and the file system API for NIO was introduced as an extension in Java 7.
🌐
Vultr Docs
docs.vultr.com › java › examples › convert-file-to-byte-array-and-vice-versa
Java Program to Convert File to byte array and Vice-Versa | Vultr Docs
December 5, 2024 - Here's how to accomplish this using Java: Import java.io.File and java.io.FileOutputStream. Create a method that accepts a byte array and a file path. Write the byte array to the file using FileOutputStream.
🌐
GeeksforGeeks
geeksforgeeks.org › java › convert-byte-array-to-file-using-java
Convert byte[] array to File using Java - GeeksforGeeks
July 11, 2025 - // Java Program to Convert Integer, ... File(FILEPATH); // Method 1 // Writing the bytes into a file static void writeByte(byte[] byteInt, byte[] byteChar, byte[] byteDouble) { // Try block to check for exceptions try { // Initialize ...
🌐
Mkyong
mkyong.com › home › java › java – how to save byte[] to a file
Java - How to save byte[] to a file - Mkyong.com
September 17, 2020 - // bytes = byte[] Path path = Paths.get("/path/file"); Files.write(path, bytes);
🌐
Level Up Lunch
leveluplunch.com › java › examples › write-byte-array-to-file
Write byte array to file | Level Up Lunch
October 28, 2013 - @Test 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); } This snippet will show how to write the content of a byte array to a file using guava Files utility class. @Test public void convert_byte_array_to_file_guava () throws IOException { File fileToWriteTo = new File(OUTPUT_FILE_NAME); Files.write(fileAsByteArray, fileToWriteTo); } Apache commons has a similar method above for writing a byte array to a file.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › java › java write byte to file
How to Write Byte to File in Java | Delft Stack
February 2, 2024 - The write() method takes the byte array as an argument and writes b.length bytes from the byte array b to this file output stream. A file with the extension .txt is created at the given path, and if we open that, we can see the contents same ...
🌐
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - package com.mkyong.io.howto; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileToBytes { public static void main(String[] args) { try { String filePath = "/home/mkyong/test/phone.png"; // file to bytes[] byte[] bytes = Files.readAllBytes(Paths.get(filePath)); // bytes[] to file Path path = Paths.get("/home/mkyong/test/phone2.png"); Files.write(path, bytes); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } } $ git clone https://github.com/mkyong/core-java · $ cd java-io · FileInputStream JavaDoc · Files JavaDoc · Apache Commons IO · Java – How to save byte arrays to a file ·
🌐
Programiz
programiz.com › java-programming › examples › convert-file-byte-array
Java Program to Convert File to byte array and Vice-Versa
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ByteFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String finalPath = System.getProperty("user.dir") + "\\src\\final.txt"; try { byte[] encoded = Files.readAllBytes(Paths.get(path)); Files.write(Paths.get(finalPath), encoded); } catch (IOException e) { } } } When you run the program, the contents of test.txt is copied to final.txt. In the above program, we've used the same method as Example 1 to read all the bytes from the File stored in path. These bytes are stored in the array encoded.
🌐
TutorialsPoint
tutorialspoint.com › How-to-write-contents-of-a-file-to-byte-array-in-Java
How to write contents of a file to byte array in Java?
December 19, 2019 - The FileInputStream class contains a method read(), this method accepts a byte array as a parameter and it reads the data of the file input stream to given byte array. import java.io.File; import java.io.FileInputStream; public class FileToByteArray { public static void main(String args[]) ...
🌐
CodeJava
codejava.net › java-se › file-io › how-to-read-and-write-binary-files-in-java
How to Read and Write Binary Files in Java
January 7, 2022 - write(byte[]): writes the specified array of bytes to the output stream. Moving down, the implementation classes FileInputStream and FileOutputStream are for reading and writing streams of raw bytes, one or multiple bytes at a time.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › io › fileoutputstream
Write byte array to file with FileOutputStream - Java Code Geeks
October 26, 2013 - Write bytes from a specified byte array to this file output stream, using write(byte[] b) API method. Don’t forget to close the stream, using its close() API method. Let’s take a look at the code snippet that follows: package com.javaco...
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › io › bufferedoutputstream
Write byte array to file with BufferedOutputStream - Java Code Geeks
October 26, 2013 - Create a BufferedOutputStream for the FileOutputStream. Use write(byte[] b) API method. It writes the specified byte array to this buffered output stream, ... package com.javacodegeeks.snippets.core; import java.io.BufferedOutputStream; import ...
🌐
W3Docs
w3docs.com › java
byte[] to file in Java
import java.io.FileOutputStream; ... file.txt. It then writes the contents of the bytes array to the file using the write() method of the FileOutputStream....
🌐
Coderanch
coderanch.com › t › 278091 › java › writing-byte-array-file
writing byte array into a file (I/O and Streams forum at Coderanch)
when i print that byte arrray in console by creating an equivalent String object things worked fine. But at the same time when i tried to store that byte array in File. its not get stored.
Top answer
1 of 3
8

You can use existing collections Like e.g. List to maintain List of byte[] and transfer it

    List<byte[]> list = new ArrayList<byte[]>();
    list.add("HI".getBytes());
    list.add("BYE".getBytes());

    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
            "test.txt"));
    out.writeObject(list);

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(
            "test.txt"));
    List<byte[]> byteList = (List<byte[]>) in.readObject();

    //if you want to add to list you will need to add to byteList and write it again
    for (byte[] bytes : byteList) {
        System.out.println(new String(bytes));
    }

Output:

   HI
   BYE

Another option is use RandomAccessFile. Which will not force you to read complete file and you can skip the data that you don't want to read.

     DataOutputStream dataOutStream = new DataOutputStream(
            new FileOutputStream("test1"));
    int numberOfChunks = 2;
    dataOutStream.writeInt(numberOfChunks);// Write number of chunks first
    byte[] firstChunk = "HI".getBytes();
    dataOutStream.writeInt(firstChunk.length);//Write length of array a small custom protocol
    dataOutStream.write(firstChunk);//Write byte array

    byte[] secondChunk = "BYE".getBytes();
    dataOutStream.writeInt(secondChunk.length);//Write length of array
    dataOutStream.write(secondChunk);//Write byte array

    RandomAccessFile randomAccessFile = new RandomAccessFile("test1", "r");
    int chunksRead = randomAccessFile.readInt();
    for (int i = 0; i < chunksRead; i++) {
        int size = randomAccessFile.readInt();
        if (i == 1)// means we only want to read last chunk
        {
            byte[] bytes = new byte[size];
            randomAccessFile.read(bytes, 0, bytes.length);
            System.out.println(new String(bytes));
        }
        randomAccessFile.seek(4+(i+1)*size+4*(i+1));//From start so 4 int + i* size+ 4* i ie. size of i
    }

Output:

BYE
2 of 3
1

You have to described your data in your encoding. i.e. add some metadata.

For example, the length of the array, then the data of the array.

This is called serialization.

Array of int: length(4 bytes), data[0] (4 bytes), data[1] (4 bytes), data[2] (4 bytes)
Top answer
1 of 4
6

Writing the file byte by byte will incur the overhead of a system call for every single byte.

Fortunately, there's an overload of write that takes an entire byte[] and writes it out with far fewer system calls:

try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {               
    fileOutputStream.write(responseBytes);
}
2 of 4
3

In your current code, you're writing to the file using a loop:

for (int ii=0; ii<responseBytes.length; ii++) {
    fileOutputStream.write(responseBytes, ii, 1);
}

This will write one byte at a time to the file output stream. Each call to fileOutputStream.write() incurs overhead because of method invocation and possibly disk I/O operations. Instead of writing one byte at a time, you can write the entire byte array in a single call:

// Write the entire byte array at once - much faster
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile){
    fileOutputStream.write(responseBytes);
}

However, for even better performance, wrap your FileOutputStream in a BufferedOutputStream as follows:

import java.io.BufferedOutputStream;

// ...

try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
    bufferedOutputStream.write(responseBytes);
}

Finally, I think that you have to go even beyond that and try not to read the entire file into memory, which can cause high memory consumption. you can directly stream the object into file skipping load it into memory.. Here How you can stream it directly into files skipping memory:

// Get the response input stream from S3
ResponseInputStream<GetObjectResponse> s3InputStream = s3Client.getObject(request);

// Define the path to the output file
File outputFile = new File(downloadPath);

try (InputStream inputStream = s3InputStream;
     OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {

    byte[] buffer = new byte[8192]; // Buffer size can be adjusted
    int bytesRead;

    // Read and write in chunks
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

} catch (IOException e) {
    e.printStackTrace();
    // Handle exceptions appropriately
}