Java: how to read a binary file 

Joined:
04/09/2007
Posts:
773

January 29, 2010 22:07:44    Last update: January 29, 2010 22:07:44
This class demonstrates how to read a binary file in Java. This is the Java version of cat, probably one of the first programs you ever use on a *NIX platform.

import java.io.*;

public class JavaCat {
    private static final int BUFFER_SIZE = 4096;

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            System.out.println("Usage: java " 
                              + JavaCat.class.getName()
                              + " <input file>");
            System.exit(1);
        }

        String fileName = args[0];

        // nested initialization, 
        // or in design pattern jargon, decorate FileInputStream with
        // BufferedInputStream.
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            int n = in.read(buffer, 0, BUFFER_SIZE);
            while (n >= 0) {
                processBuffer(buffer, 0, n);
                n = in.read(buffer, 0, BUFFER_SIZE);
            }
        }
        finally { // always close input stream
            in.close();
        }
    }

    private static void processBuffer(byte[] buffer, int start, int end) {
        System.out.write(buffer, start, end);
    }
}
Share |
| Comment  | Tags