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);
}
}
}
CRC32 checksum calculation Java NIO
Upasana | 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
Java’s FileChannel’s provide much better performance than the BufferedInputStream and RandomAccessFile classes.
Top articles in this category:
- Http download using Java NIO FileChannel
- Factorial of a large number in Java BigInteger
- Code review checklist for Java developers
- Count word frequency in Java
- Producer Consumer Problem using Blocking Queue in Java
- What is Double Checked Locking Problem in Multi-Threading?
- Precision and scale for a Double in java
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..