Creating a checksum of an InputStream

Use the class CheckedInputStream. This class is a FilterInputStream and calculates a checksum as data passes through it. When creating it, pass it an existing inputstream and an instance of a class that implements the Checksum interface. In the standard API, there are two such classes available: java.util.zip.Adler32 and java.util.zip.CRC32.
The checksum value can be retrieved by invoking getChecksum().getValue().

This method calculates the checksum of a file.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
         System.exit(1);
      }
 
      File file = new File(args[0]);
      CheckedInputStream cis = new CheckedInputStream(new FileInputStream(file), 
                                                      new CRC32());
      byte []buffer = new byte[1024];
      while (cis.read(buffer) > 0) { }
      cis.close();
 
      System.out.println("Checksum of file " + args[0] + " = " 
                            + cis.getChecksum().getValue());
    }
}