CRC32 checksum calculation Java NIO

Carvia Tech | December 04, 2019 | 1 min read | 87 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
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 =, 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 (FileNotFoundException e) {
     } catch (IOException e) {
     throw new RuntimeException("unknown IO error occurred ");

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
  3. Is Java Pure Object Oriented Language?
  4. Precision and scale for a Double in java
  5. Comparable vs Comparator in Java
  6. Troubleshooting Deadlock in Java
  7. can we write a java method that swaps two integers

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago

Recommended books for interview preparation:

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