Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java write binary file

farenda 2016-02-16 0

Problem:

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.

Solution:

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

  1. java.io.FileWriter for text files.
  2. java.io.FileOutputStream 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:

package com.farenda.java.io;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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!
Categories Java Tags java, java-io
Previous: Java read text file
Next: Java read binary file

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored