Home > Java > javaTutorial > How Can I Efficiently Calculate MD5 Checksums in Java?

How Can I Efficiently Calculate MD5 Checksums in Java?

Barbara Streisand
Release: 2025-01-01 11:03:10
Original
692 people have browsed it

How Can I Efficiently Calculate MD5 Checksums in Java?

Calculating MD5 Checksums with Java Streams

In Java, obtaining the MD5 checksum of a file can be achieved seamlessly using the DigestInputStream decorator. This stream decorator computes the digest as you read the input stream, eliminating the need for additional data passes.

Implementation:

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

By utilizing the DigestInputStream, you can compute the MD5 checksum while simultaneously reading the input stream, offering an efficient and time-saving approach.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template