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:
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!