Home Tutorial Java Core Files Java file checksum

 
 

Share on Google+Share on Google+
Java file checksum
Posted on: August 1, 2006 at 12:00 AM
Advertisement
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:

import java.io.*;
import java.util.zip.*;

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 (in.read() != -1) {
		}
		System.out.println("Checksum is: " + cis.getChecksum().getValue());
	}
}

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

Output:

Checksum is: 2845602957
Advertisement

Related Tags for Java file checksum:


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.

Posted on: August 1, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com