How do I create a checksum for a file?

Tim Rohaly

Java has two stream classes which may be used to calculate checksums: java.util.zip.CheckedInputStream and java.util.zip.CheckedOutputStream. Both of these streams require a constructor argument, of type java.util.zip.Checksum, which is used to specify the checksum algorithm. Two algorithm implementations, Adler32 and CRC32, are provided in the java.util.zip package, or you may implement the Checksum interface for your own algorithm.

Here's a short example of how to calculate the checksum for a file (specified by a command-line argument), using the CRC32 algorithm:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.zip.Checksum;
import java.util.zip.CheckedInputStream;
import java.util.zip.CRC32;

public class checksum {

    public static void main(String[] args) 
      throws IOException {
        
        FileInputStream file = new FileInputStream(args[0]);
        CheckedInputStream check = 
          new CheckedInputStream(file, new CRC32());
        BufferedInputStream in = 
          new BufferedInputStream(check);
        while (in.read() != -1) {
            // Read file in completely
        }
        System.out.println("Checksum is " + 
          check.getChecksum().getValue());
    }
}

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact