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

public void readFile(String fileName) throws IOException {
    File fileTobeRead = new File(fileName);

    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileTobeRead));
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead = 0;
    long fileSize = 0;
    while((bytesRead = bufferedInputStream.read(data)) != -1) {
      fileSize += bytesRead;
      // process the byte[] upto the bytesRead
    }
    System.out.println(String.format("File size is = %d KB", (fileSize / 1024)));
  }

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

package com.codezuzu.algo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * codezuzu.com
 */
public class BinaryFileReading {

  public static final int BUFFER_SIZE = 64 * 1024;

  public void readFile(String fileName) throws IOException {
    File fileTobeRead = new File(fileName);

    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileTobeRead));
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead = 0;
    long fileSize = 0;
    while((bytesRead = bufferedInputStream.read(data)) != -1) {
      fileSize += bytesRead;
      // process the byte[] upto the bytesRead
    }
    System.out.println(String.format("File size is = %d KB", (fileSize / 1024)));
  }

  public static void main(String[] args) throws IOException {
    BinaryFileReading binaryFileReading = new BinaryFileReading();
    binaryFileReading.readFile(args[0]);
  }

}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.