Tuesday, May 28, 2013

Efficient way to calculate Checksum of a file in using Java FileChannel

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.

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) {
     } catch (IOException e) {
     throw new RuntimeException("unknown IO error occurred ");

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

No comments:

Post a Comment

Your comment will be published after review from moderator