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: and
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.

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());
      System.out.println("Checksum of outputstream = " + 
                               + cis.getChecksum().getValue());


Checksum of outputstream = 3957769958