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();
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!