How to read binary files in Java

In the post, How to read Text Files in Java, we saw how to read text file. At times we have a need that we have binary files like images or compressed file that we want to read. We cannot use Reader’s and sub-classes for it. Let’s quickly see how to do this.

Reading Binary Files

Let’s see the code to read binary file

We use BufferedInputStream for this. The code is similar to BufferedReader, with a minor change. BufferedReader provides a readLine() API, but when reading binary files, we don’t have a notion of line, hence we need to use a byte[] and read the data. Important thing to note is that the read API returns the number of bytes read, which means you need to process buffer only till length specified by number returned by API, in our case bytesRead.

In the example, we just calculated the file size, you can add processing logic inside the loop. Like for file copy, you can write the buffer to OutputStream.

Everything Together

Leave a Reply

Your email address will not be published. Required fields are marked *