Java I/O How to - Calculate Checksum CRC32








Question

We would like to know how to calculate Checksum CRC32.

Answer

// w  ww .j  a v a  2s.  c o  m
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.zip.CRC32;

public class Main {
  public static void main(String[] args) throws Exception{
    BufferedInputStream is = new BufferedInputStream(new FileInputStream("a.exe"));
    byte[] bytes = new byte[1024];
    int len = 0;

    while ((len = is.read(bytes)) >= 0) {
      new CRC32().update(bytes, 0, len);
    }
    is.close();
    System.out.println(Arrays.toString(bytes));

  }
}

Another solution:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/*from  w ww.j a v  a2 s  .c o  m*/
public class Main {

  public static void main(String[] args) throws IOException {
    FileInputStream fin = new FileInputStream("a.zip");
    Checksum cs = new CRC32();
    for (int b = fin.read(); b != -1; b = fin.read()) {
      cs.update(b);
    }
    System.out.println(cs.getValue());
    fin.close();
  }
}