Home >Java >javaTutorial >How to Calculate an MD5 File Checksum in Java?

How to Calculate an MD5 File Checksum in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 17:45:141014browse

How to Calculate an MD5 File Checksum in Java?

Obtaining an MD5 File Checksum Utilizing Java

Despite the extensive capabilities of Java, a query concerning the computation of MD5 checksums for files initially garnered no straightforward solutions. To address this gap, we present a detailed illustration outlining the process using the DigestInputStream class.

The DigestInputStream functions as an input stream decorator, allowing for the simultaneous calculation of a digest while accessing the input stream as usual. This obviates the need for a separate data pass.

The following code snippet exemplifies the use of DigestInputStream:

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

In this code:

  • md represents an instance of the MD5 message digest algorithm.
  • is is an input stream for the target file.
  • dis is the DigestInputStream object that wraps is, performing MD5 calculation while reading the file.
  • md.digest() retrieves the computed MD5 digest as an array of bytes.

Using this approach, you can effortlessly obtain the MD5 checksum of a file in Java.

The above is the detailed content of How to Calculate an MD5 File Checksum 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