Compute Checksum of File in Java using Apache Commons IO
Tags: FileUtils Apache Commons Apache Commons IO File CRC32 Adler32 Checksum
In this Java tutorial, we learn how to compute the Adler-32 or CRC-32 checksum value of a file using FileUtils class of Apache Commons IO library.
How to add Apache Commons IO library to your Java project
To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'commons-io:commons-io:2.8.0'
To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/
Compute CRC-32 Checksum of a File
To compute the CRC-32 checksum value we can use FileUtils.checksum() method with the CRC32 object as an argument as in the following Java program.
ChecksumFile1.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.zip.CRC32;
public class ChecksumFile1 {
public static void main(String... args) {
try {
File file = new File("D:\\Data\\data.txt");
long checksumValue = FileUtils.checksum(file, new CRC32()).getValue();
System.out.println("Checksum value of file " + file + " is " + checksumValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Checksum value of file D:\Data\data.txt is 1477812112
FileUtils class also provides the method FileUtils.checksumCRC32() to compute CRC-32 checksum value.
ChecksumFile2.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ChecksumFile2 {
public static void main(String... args) {
try {
File file = new File("D:\\Data\\data.txt");
long checksumValue = FileUtils.checksumCRC32(file);
System.out.println("Checksum value of file " + file + " is " + checksumValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Checksum value of file D:\Data\data.txt is 1477812112
Compute Adler-32 Checksum of a File
To compute the Adler-32 checksum value we can use FileUtils.checksum() method with the Adler32 object as argument as in the following Java program.
ChecksumFile3.java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.zip.Adler32;
public class ChecksumFile3 {
public static void main(String... args) {
try {
File file = new File("D:\\Data\\data.txt");
long checksumValue = FileUtils.checksum(file, new Adler32()).getValue();
System.out.println("Checksum value of file " + file + " is " + checksumValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Checksum value of file D:\Data\data.txt is 3418430849
Happy Coding 😊