CRC32 checksum calculation Java NIO

Carvia Tech | November 21, 2020 | 1 min read | 100 views


Few of the times we wish the speed of C and syntax of Java for doing some IO intensive task in Java. Calculation of CRC is one of them task which requires a efficient implementation in order to give good performance.

CRC32 calculation in Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.CRC32;

class Scratch {

    public static long calculateCRC(File filename) {
        final int SIZE = 16 * 1024;
        try (FileInputStream in = new FileInputStream(filename);) {
            FileChannel channel = in.getChannel();
            CRC32 crc = new CRC32();
            int length = (int) channel.size();
            MappedByteBuffer mb = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
            byte[] bytes = new byte[SIZE];
            int nGet;
            while (mb.hasRemaining()) {
                nGet = Math.min(mb.remaining(), SIZE);
                mb.get(bytes, 0, nGet);
                crc.update(bytes, 0, nGet);
            }
            return crc.getValue();
        } catch (IOException e) {
            throw new RuntimeException("unknown IO error occurred ", e);
        }
    }
}

Java’s FileChannel’s provide much better performance than the BufferedInputStream and RandomAccessFile classes.


Top articles in this category:
  1. Http download using Java NIO FileChannel
  2. Factorial of a large number in Java BigInteger
  3. Code review checklist for Java developers
  4. Count word frequency in Java
  5. Producer Consumer Problem using Blocking Queue in Java
  6. What is Double Checked Locking Problem in Multi-Threading?
  7. Precision and scale for a Double in java

Find more on this topic:

Recommended books for interview preparation:
Buy interview books

Java & Microservices interview refresher for experienced developers.


This website uses cookies to ensure you get the best experience on our website. more info