Home >Java >javaTutorial >How to Compute MD5 File Checksums in Java?

How to Compute MD5 File Checksums in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 21:07:33136browse

How to Compute MD5 File Checksums in Java?

Computing MD5 File Checksums in Java

Java provides extensive support for cryptography operations, including calculating file MD5 checksums. Here's how you can achieve this:

To compute an MD5 checksum for a file, you can use the DigestInputStream class. It extends InputStream and allows you to compute the digest while reading the input stream, avoiding the need for additional passes over the data:

MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
     DigestInputStream dis = new DigestInputStream(is, md)) {
  /* Read the decorated stream (dis) to end-of-file as usual... */
}
byte[] digest = md.digest();

The digest variable now contains the MD5 checksum of the file. This technique is efficient and eliminates the need to manually iterate over the file contents to compute the checksum.

The above is the detailed content of How to Compute MD5 File Checksums in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn