Calculating the Adler32 checksum of a file.


 

Calculating the Adler32 checksum of a file.

In this tutorial you will see how to Calculating the Adler32 checksum of a file.

In this tutorial you will see how to Calculating the Adler32 checksum of a file.

Calculating the Adler32 checksum of a file.

In this tutorial, we will discuss the use of Adler32 class. The Adler32 class used to compute the checksum of data stream.It creates a input stream for reading bytes from file. The Adler32 class class is available in java.util.zip package. Alder32 checksum work faster then CRC32.

With the help of this example, you will see how to compute the Adler32 checksum of file. First of all, we will create an object of Adler32. The FileInputStream class create input stream for reading bytes from file.The CheckedOutputStream class is used to compute the checksum of the data begin written on the output stream. The getValue() method of  the Adler32 class return value of checksum, and reset() method of  the Adler32 class reset the checksum value with initial value.

About Adler32 API:

The java.util.zip.Adler32 class extends java.lang.Object class. It provide following methods:

Return Type Method Description 
checksum getValue()  The getValue() method returns value of checksum. 
void reset()  The reset() method  reset the checksum value at initial value.

Code

import java.util.zip.CheckedInputStream;
import java.util.zip.Adler32;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

class AdlerCheckSum {
  public static void main(String[] args) {
    try {
      String fileName = "testfile.txt";
      FileInputStream inputStream = new FileInputStream(fileName);
      Adler32 adlerChecksum = new Adler32();
      File file = new File(fileName);
      long firstValue = adlerChecksum.getValue();
      System.out.println("value of Adler32 checkSum :" + firstValue);
      CheckedInputStream cinStream = new CheckedInputStream(inputStream,
          adlerChecksum);
      long fileSize = file.length();
      byte[] b = new byte[128];
      while (cinStream.read(b>= 0) {
      }
      long checksum = cinStream.getChecksum().getValue();
      System.out.println("Name of file : " + fileName);
      System.out
      .println("value of Adler32 checkSum after reading a file :"
          + checksum);
      adlerChecksum.reset();
      long resetValue = adlerChecksum.getValue();
      System.out.println("value of Adler32 CheckSum After reseting :"
          + resetValue);
    catch (IOException e) {
      System.out.println("IOException : " + e);
    }
  }
}

Following is the output if you run the application :

C:\>java AdlerCheckSum
value of Adler32 checkSum :1
Name of file : testfile.txt
value of Adler32 checkSum after reading a file :1843857417
value of Adler32 CheckSum After reseting :1

Download this code

Ads