Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java read binary file


How to read binary file in Java? The simplest solution is to use FileInputStream with try-with-resources as this in this example.

In the last post we’ve shown how to write binary file. In this post we’re going to show how to read it back into our Java program.


The solution is simple, we’re going to use, but because our binary data is a string we’ll add one twist to the code. We are going to use to read it. To do that we’ll pass the InputStream into InputStreamReader to turn it into the Reader and read as any other string! If we wouldn’t do that, then we would need to read byte array and then turn it into a String.

Let’s see the code:


import java.nio.charset.StandardCharsets;

public class ReadBinaryFileExample {

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

        StringBuilder sb = new StringBuilder();
        try (BufferedReader input = openFile(dataFile)) {
            String line;
            while ((line = input.readLine()) != null) {

        System.out.println("Data from file:\n" + sb);

    private static BufferedReader openFile(String fileName)
            throws IOException {
        // Don't forget to add buffering to have better performance!
        return new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(fileName),

Now, let’s say that we’ve got binary file with the following content:

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

If we run the above program, the output is this:

Data from file:
Saluton, mondo!Some more data!
Share with the World!