Share on Google+Share on Google+

Java file checksum

In this section, you will learn how to calculate the checksum for a file.

Java file checksum

In this section, you will learn how to calculate the checksum for a file.

Description of code:

While transferring a file, checksum is used for error checking. The data flows in the form of packets and for each packet there is a different checksum value. This value is transmitted with the packets. The system checks the checksum and according to which it receives and rejects the packets.

In the given example, we have used CheckedInputStream and BufferedInputStream class to compute the checksum for a file.

CheckedInputStream: This class maintains the checksum of the data to be read.

Adler32: This class computes the Alder-32 checksum of the stream.

BufferedInputStream: This class adds functionality to another input stream. It provides the ability to buffer the input.

getCheckSum(): This method of CheckedInputStream class returns the Checksum for the input stream.

getValue(): This method of interface Checksum returns the current checksum value.

Here is the code:


public class FileChecksum {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream(new File("C:/data.txt"));
		CheckedInputStream cis = new CheckedInputStream(fis, new CRC32());
		BufferedInputStream in = new BufferedInputStream(cis);
		while ( != -1) {
		System.out.println("Checksum is: " + cis.getChecksum().getValue());

Through the above code, you can compute the checksum for the given file.


Checksum is: 2845602957


Posted on: August 1, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.