That's not how it works. a java.io.File object is a light wrapper: Check out the source code - it's got a String field that contains the path and that is all it has aside from some bookkeeping stuff.

It is not possible to represent arbitrary data with a java.io.File object. j.i.File objects represent literal files on disk and are not capable of representing anything else.

Files.readAllBytes gets you the contents from the bytes, that's.. why the method has that name.

The usual solution is that a method in some library that takes a File is overloaded; there will also be a method that takes a byte[], or, if that isn't around, a method that takes an InputStream (you can make an IS from a byte[] easily: new ByteArrayInputStream(byteArr) will do the job).

If the API you are using doesn't contain any such methods, it's a bad API and you should either find something else, or grit your teeth and accept that you're using a bad API, with all the workarounds that this implies, including having to save bytes to disk just to satisfy the asinine API.

But look first; I bet there is a byte[] and/or InputStream variant (or possibly URL or ByteBuffer or ByteStream or a few other more exotic variants).

Answer from rzwitserloot 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
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.
๐ŸŒ
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.
๐ŸŒ
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, Character and Double // Types into Bytes and Writing it in a File // Importing required classes import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; // Main class public class GFG { // Path of a file static String FILEPATH = ""; // Getting the file via creating File class object static File file = new 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 a pointer in file // using OutputStre
๐ŸŒ
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 ...
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.

Find elsewhere
๐ŸŒ
W3Docs
w3docs.com โ€บ java
byte[] to file in Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) { byte[] bytes = {1, 2, 3}; try { Files.write(Paths.get("file.txt"), bytes); } catch (IOException e) { e.printStackTrace(); } } } Copy ยท This code writes the bytes array to the file file.txt using the write() method of the Files class. Tags ยท inputstream java file arrays io ยท How do I check whether a file exists without exceptions?
๐ŸŒ
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 ...
๐ŸŒ
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.
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
}
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ 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
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 31058770 โ€บ create-file-from-byte-array-without-saving-to-file-directory
java - Create file from byte array without saving to file directory - Stack Overflow
June 25, 2015 - @Deprecated public static ParcelFileDescriptor fromData(byte[] data, String name) throws IOException { if (data == null) return null; MemoryFile file = new MemoryFile(name, data.length); if (data.length > 0) { file.writeBytes(data, 0, 0, data.length); } file.deactivate(); FileDescriptor fd = file.getFileDescriptor(); return fd != null ?
๐ŸŒ
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.
๐ŸŒ
Program Creek
programcreek.com โ€บ 2009 โ€บ 02 โ€บ java-convert-a-file-to-byte-array-then-convert-byte-array-to-a-file
Java: convert a file to a byte array, then convert byte array to a file. โ€“ Program Creek
February 20, 2009 - To convert byte array back to the original file, FileOutputStream class is used. A file output stream is an output stream for writing data to a File or to a FileDescriptor. The following code has been fully tested. import java.io.ByteArrayOutputStream; import java.io.File; import ...
Top answer
1 of 2
3

You can read images directly from byte streams with the ImageIO class. Assuming of course that you have previously written the image data in a compatible format. Which is hard to say given the fact that in your code you use an intermediary object input stream when reading your byte data. Here's an example of how you can create an image directly from the database without using intermediary files:

bais = new ByteArrayInputStream(resultSet.getBytes("image"));
final BufferedImage image = ImageIO.read(bais);
// pass the image to your Swing layer to be rendered.

And an example of how you would have written the data to the database, in order to be able to use this code:

final ByteArrayOutputStream baos = new ByteArrayOutputStream(64000);
ImageIO.write(image, "PNG", baos);
final byte[] data = baos.toByteArray();
// write data to database
2 of 2
0

The answer to your question is its platform dependent. From the docs

A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

So if you want to write to a file then file may or may not be created.

If you don't want to create the file and you are just interested in byte[] (content of the file) you can then use solution provided by @Perception or can just pass the inputStream that you have already created.

๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ java โ€บ programs โ€บ byte-array-to-file
Java Program to Convert Byte Array to File (3 Programs)
October 18, 2025 - Learn how to convert a byte array to a file in Java using 3 simple programs. Explore step-by-step examples with outputs and explanations. Read now!