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
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ writing byte[] to a file in java
Writing byte[] to a File in Java | Baeldung
December 11, 2025 - 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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ convert-byte-array-to-file-using-java
Convert byte[] array to File using Java - GeeksforGeeks
July 11, 2025 - As we know whenever it comes to ... order to convert a byte array to a file, we will be using a method named the getBytes() method of String class....
๐ŸŒ
FrontBackend
frontbackend.com โ€บ java โ€บ convert-byte-array-to-file-in-java
Convert Byte Array to File In Java | FrontBackend
August 25, 2020 - In this article we are going to present how to convert Byte Array to File using plain Java solutions (also in version JDK7) and libraries like Guava and Apache Commons IO.
๐ŸŒ
Aviator Dao
java2novice.com โ€บ ะณะปะฐะฒะฝะฐั ัั‚ั€ะฐะฝะธั†ะฐ โ€บ welcome to aviator dao from the creators of the java2novice
Program: How to write byte content to a file in java?
July 17, 2024 - Discover the evolution of our journey from Java programming tutorials to the exciting world of the Aviator Game. At Aviator DAO, we provide in-depth guides, strategies, and resources for mastering Aviator.
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ byte-array-to-file-in-java-without-overwriting
Java Byte Array to File: Complete 2026 Guide with Latest Features and Best Practices - Java byte array to file
November 10, 2025 - Mastering byte array to file conversion in Java requires understanding both classic and modern APIs while adopting 2026 best practices. The Files.write() method from Java NIO provides the optimal balance of simplicity, performance, and safety for most use cases.
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 ...
๐ŸŒ
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 - Note that this method overwrites a file with the contents of a byte array. File file = new File("test.txt"); byte[] bytes = "testData".getBytes(); com.google.common.io.Files.write(bytes, file); In this short Java tutorial, we learned to write the byte array content into a file using various Java APIs; and Commons IO and Guave libraries.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ convert-byte-array-to-file-using-java
Convert byte[] array to File using Java
June 17, 2024 - Step 2 Declare and import the Java packages. Step 3 Declare a public class. Step 4 Declare a method which convert a byte array into Writer Class. Step 5 Declare a static byte type. Step 6 Declare a file writer class. Step 7 Declare a Call append() method. Step 8 Costruct a driver code. Step 9 Declare the various values. Step 10 Call the main method. Step 11 Get the return value as a file. Step 12 Terminate the process. FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray) try (FileOutputStream fos = new FileOutputStream("pathname")) { fos.write(myByteArray); } try (FileOutputStream
๐ŸŒ
Initial Commit
initialcommit.com โ€บ blog โ€บ java-convert-byte-to-file
Java โ€“ Convert byte[] to File - Initial Commit
public static File convertUsin... ex.printStackTrace(); } return f; } With Java 7, you can do the conversion using Files utility class of nio package: public static File convertUsingJavaNIO(byte[] fileBytes) { File f = new ...
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ convert-file-byte-array
Java Program to Convert File to byte array and Vice-Versa
Then, we simply use the Files' write() method to write the encoded byte array to a File in the given finalPath. ... Your builder path starts here.
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
7 Examples to Read File into a byte array in Java - Java Code Geeks
April 27, 2020 - Something Java has been lacking from the first edition. By the way, this method is only intended for simple use where it is convenient to read all bytes into a byte array. It is not intended for reading large files and throws OutOfMemoryError, if an array of the required size cannot be allocated, for example, the file is larger than 2GB. By the way, if you only have File object and not Path then you can also use File.toPath() to convert File to Path in JDK 1.7.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2020 โ€บ 04 โ€บ 7-examples-to-read-file-into-byte-array-in-java.html
7 Examples to Read File into a Byte Array in Java
July 28, 2021 - Something Java has been lacking from the first edition. By the way, this method is only intended for simple use where it is convenient to read all bytes into a byte array. It is not intended for reading large files and throws OutOfMemoryError, if an array of the required size cannot be allocated, for example, the file is larger than 2GB. By the way, if you only have File object and not Path then you can also use File.toPath() to convert File to Path in JDK 1.7.
Top answer
1 of 3
5

You're opening a new FileOutputStream on each iteration of the loop. Don't do that. Open it outside the loop, then loop and write as you are doing, then close at the end of the loop. (If you use a try-with-resources statement with your while loop inside it, that'll be fine.)

That's only part of the problem though - you're also doing everything else on each iteration of the loop, including checking for headers. That's going to be a real problem if the byte array you read contains part of the set of headers, or indeed part of the header separator.

Additionally, as noted by EJP, you're ignoring the return value of read apart from using it to tell whether or not you're done. You should always use the return value of read to know how much of the byte array is actually usable data.

Fundamentally, you either need to read the whole response into a byte array to start with - which is easy to do, but potentially inefficient in memory - or accept the fact that you're dealing with a stream, and write more complex code to detect the end of the headers.

Better though, IMO, would be to use an HTTP library which already understands all this header processing, so that you don't need to do it yourself. Unless you're writing a low-level HTTP library yourself, you shouldn't be dealing with low-level HTTP details, you should rely on a good library.

2 of 3
1

Open the file ahead of the loop.

NB you need to store the result of read() in a variable, and pass that variable to new String() as the length. Otherwise you are converting junk in the buffer beyond what was actually read.

๐ŸŒ
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 - In this article, you will learn how to convert files to byte arrays and then convert those byte arrays back into files using Java.
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
}
๐ŸŒ
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.