Calculating the checksum of a byte array using CRC32

Use the CRC32 class in the java.util.zip package. It contains an implementation of an algorithm to calculate the checksum of a set of bytes. It is slighly slower than Adler32, a class with the same purpose, but it generates a better result.

The procedure is simple: create an instance of the CRC32 class, call its method update and provide it with a set of bytes in the order as they appear in the stream. If all bytes have been processed, call getValue to get the checksum as a String.
If you need to calculate checksums of several bytestreams, you can reuse the CRC32 instance but you need to call reset in order to reset it to its original state.

Following example displays a checksum of a file provided at command line.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      try {
         CRC32 crc32 = new CRC32();
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0]));
  
         int l = 0;
         byte[] buffer = new byte[1024];
         while ((l = bis.read(buffer)) >= 0) {
            crc32.update(buffer, 0, l);
         }
 
         System.out.println("CRC-32 checksum of file " + args[0] + ":");
         System.out.println(crc32.getValue());
      }
      catch(IOException e) {
         System.err.println(e);
      }
   }
}