Appearance
Getting a File's MD5 Checksum in Java
To get a file's MD5 checksum in Java, you can use the MessageDigest class from the java.security package. Here's an example of how you can use MessageDigest to calculate the MD5 checksum of a file:
java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
public class Main {
public static void main(String[] args) throws IOException {
try (InputStream fis = new FileInputStream("file.txt")) {
MessageDigest md = MessageDigest.getInstance("MD5");
try (DigestInputStream dis = new DigestInputStream(fis, md)) {
byte[] buffer = new byte[8192];
while (dis.read(buffer) != -1) {
// consume stream
}
}
byte[] checksum = md.digest();
System.out.println(toHexString(checksum));
}
}
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}This code reads the file in chunks using a DigestInputStream, which automatically updates the MessageDigest as data flows through. It then retrieves the final checksum and prints it as a hexadecimal string.
Note that this example uses the MessageDigest.getInstance("MD5") method to get a MessageDigest instance for the MD5 algorithm. You can use a similar approach to calculate the checksum of a file using other algorithms, such as SHA-1 or SHA-256. Just replace the string passed to getInstance() with the name of the desired algorithm. Note that MD5 is acceptable for non-cryptographic checksums, but for security-sensitive applications, consider using SHA-256 or stronger algorithms.