Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java write binary file


How to write binary file in Java? The simplest solution is to use FileOutputStream with try-with-resources and improved performance as show in the example.


There are two main ways to write data to files in Java:

  1. for text files.
  2. for binary data.

In the following example we’re going to show how to use FileOutputStream to create and write to a new binary file, and then how to reopen it for appending some more data:


import java.nio.charset.StandardCharsets;

public class WriteBinaryFileExample {

    public static void main(String[] args) throws IOException {
        String targetFile = "binary-file.dat";

        // Create a new file and override when already exists:
        try (OutputStream output = openFile(targetFile)) {
            output.write(getUtf8Bytes("Saluton, mondo!"));

        // Reopen the file but for appending:
        try (OutputStream output = openFile(targetFile, true)) {
            output.write(getUtf8Bytes("Some more data!"));

    private static byte[] getUtf8Bytes(String s) {
        // Always specify encoding and not rely on default!
        return s.getBytes(StandardCharsets.UTF_8);

    private static BufferedOutputStream openFile(String fileName)
            throws IOException {
        return openFile(fileName, false);

    private static BufferedOutputStream openFile(String fileName, boolean append)
            throws IOException {
        // Don't forget to add buffering to have better performance!
        return new BufferedOutputStream(new FileOutputStream(fileName, append));

The program is straightforward. We’re opening file streams in try-with-resources to have them automatically closed after use. Strings that serve as input data are converted to bytes (note the specified encoding!) and the written to FileOutputStream. Also, we’re wrapping the stream in BufferedOutputStream to have better performance – makes writing data in chunks instead of single bytes.

Let’s run the above program and verify that it works:

$> cat binary-file.dat
Saluton, mondo!Some more data!

Although we’ve used text as our input, we’ve wrote it into the file using FileOutputStream that serves for writing any binary data – contrary to text-only FileWriter.

Share with the World!