Creating a checksum of an OutputStream

Use the class CheckedOutputStream. This class is a FilterOutputStream and calculates a checksum as data passes through it. When creating it, pass it an existing outputstream 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 string as we write it to a file.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      CheckedOutputStream cis = new CheckedOutputStream(new FileOutputStream("testfile"), 
                                                        new CRC32());
 
      cis.write("Hello, world!".getBytes());
      cis.close();
 
      System.out.println("Checksum of outputstream = " + 
                               + cis.getChecksum().getValue());
    }
}

outputs:

Checksum of outputstream = 3957769958