How to use update and reset method of CRC32


 

How to use update and reset method of CRC32

In this tutorial you will see how to use update and reset method of CRC32.

In this tutorial you will see how to use update and reset method of CRC32.

How to use update and reset method of CRC32.

In this tutorial, we will discuss about the update() and reset() method of CRC32 class. The 
CRC32 class is used to compute the checksum of data stream. The CRC32 class is available in
  java.util.zip package . 

In this example, you will see how to update the CRC32 checksum. The FileInputStream class create 
input stream for reading bytes from file.  The read() method  of  FileInputStream class read bytes from
this input stream and store it  into a array of  bytes. ThegetValue() method of the CRC32 class returns
the value of checksum. The update(byte[] buffer, int offset, int length) method of the CRC32 class
update the value of checksum with array of bytes, and the reset() method of  the CRC32 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 update(byte[] buff, int offset, int length) The update() method update checksum with array of bytes.
void reset()  The reset() method  reset the checksum value at initial value.

Code

import java.util.zip.CRC32;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

class CrcCheckSum {
  public static void main(String[] args) {
    try {
FileInputStream inputStream = new FileInputStream("testfile.txt");
      CRC32 crcChecksum = new CRC32();
      long initialValue = crcChecksum.getValue();
      System.out.println("Initial value of CRC32 checkSum :"
          + initialValue);
      byte[] b = new byte[128];
      while (inputStream.read(b>= 0) {
      }
      crcChecksum.update(b, 0, b.length);
      long update = crcChecksum.getValue();
    System.out.println("After updating the value of  check sum : "
          + update);
      crcChecksum.reset();
      long resetValue = crcChecksum.getValue();
        System.out.println("Value of CRC32 CheckSum after reset :"
          + resetValue);
    catch (IOException e) {
      System.out.println("IOException : " + e);
    }
  }
}

Following is the output if you run the application :

C:\>java CrcCheckSum
Initial value of CRC32 checkSum :0
After updating the value of CRC32 checksum : 2141301436
Value of CRC32 CheckSum after reset :0

Download this code

Ads