This post will discuss how to write to a binary file in Java.

The solution should create the file if it doesn’t exist or truncate the file before writing if it already exists. Following are some available options in Java to write bytes to a binary file.

1. Using Files Class

With Java 7, we can use Files.write(…), which writes bytes to a file efficiently. It opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing file to size 0.

Download Code

2. Using FileOutputStream

FileOutputStream is meant for writing streams of raw bytes such as image data. Here’s a working example:

Download Code

3. Using DataOutputStream

We can use a data output stream to write the string to the underlying output stream as a bytes sequence.

Download Code

4. Using Guava Library

Guava’s Files.write(byte[], File) method can be used for overwriting a file with the contents of a byte array.

Download Code

5. Using Apache Commons IO

FileUtils class from Apache Commons IO library has the writeByteArrayToFile(File, byte[]) method, which writes a byte array to a file. If the file already exists, then the file will be truncated before writing.

Download Code

6. Using FileChannel for large files

To write large binary files, use FileChannel. Note this doesn’t overwrite an existing file.

Download Code

That’s all about writing to a binary file in Java.

 
Also See:

Write to a file in Java