Writing Byte[] to a File in Java

Learn to write the given byte[] into a file using different solutions. We will be using the Java NIO, Commons IO and Guava APIs that provide simple APIs for this usecase.

1. Java NIO’s Files.write()

The Files.write() is the simplest way to write bytes into a file.

We should be very careful about the file open options while writing the bytes. By default, the CREATE, TRUNCATE_EXISTING, and WRITE options are used. It means that the method opens the file for writing, creating the file if it doesn’t exist, or initially truncating the regular file to a size of 0.

byte[] bytes = "testData".getBytes();

Path filePath = Paths.get("test.txt");
Files.write(filePath, bytes);

If we do not overwrite the file content, rather we want to append the bytes into the existing file content then we can use the StandardOpenOption.APPEND option.

byte[] bytes = "testData".getBytes();

Path filePath = Paths.get("test.txt");
Files.write(filePath, bytes, StandardOpenOption.APPEND);

If we want to create a new file, always, then we can pass the option StandardOpenOption.CREATE_NEW. It ensures that the method will throw FileAlreadyExistsException if the file already exists.

byte[] bytes = "testData".getBytes();

Path filePath = Paths.get("test.txt");
Files.write(filePath, bytes, StandardOpenOption.CREATE_NEW);

2. Using FileOutputStream

Using FileOutputStream is another good approach. We can create the output stream for a new or existing file and write the bytes to the stream.

Do not forget to close the output stream if you are not using the try-with-resources statement.

byte[] bytes = "testData".getBytes();
File file = new File("test.txt");

try (FileOutputStream os = new FileOutputStream(file)) {

3. Commons IO’s FileUtils

The FileUtils class has method writeByteArrayToFile() that writes the byte array data into the specified file. It creates a new file and its parent directories if they do not exist.

File file = new File("test.txt");
byte[] bytes = "testData".getBytes();

FileUtils.writeByteArrayToFile(file, bytes);

Include Commons IO using the latest maven dependency in the project.


4. Guava’s Files

Similar to previous solutions, Files.write() method writes the bytes to the specified file. 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);

5. Conclusion

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.

Happy Learning !!

Source Code on Github

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial