CRC32 checksum calculation Java NIO

Carvia Tech | December 04, 2019 | 1 min read | 5 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 = 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 (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
     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. How will you calculate factorial of a large number in Java
  3. Set precision and scale for a double value in java
  4. Is Java Pure Object Oriented Language?
  5. can we write a java method that swaps two integers
  6. Diamond Problem of Inheritance in Java 8
  7. What is volatile keyword in Java


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