|
| 1 | +package com.baeldung.md5checksum; |
| 2 | + |
| 3 | +import com.google.common.hash.HashCode; |
| 4 | +import com.google.common.hash.Hashing; |
| 5 | +import com.google.common.io.ByteSource; |
| 6 | +import org.apache.commons.codec.digest.DigestUtils; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.InputStream; |
| 11 | +import java.math.BigInteger; |
| 12 | +import java.nio.file.Files; |
| 13 | +import java.nio.file.Paths; |
| 14 | +import java.security.MessageDigest; |
| 15 | +import java.security.NoSuchAlgorithmException; |
| 16 | + |
| 17 | +public class Md5ChecksumGenerator { |
| 18 | + |
| 19 | + public static String genWithApacheCommons(String filePath) throws IOException { |
| 20 | + try (InputStream is = Files.newInputStream(Paths.get(filePath))) { |
| 21 | + return DigestUtils.md5Hex(is); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static String genWithGuava(String filePath) throws IOException { |
| 26 | + File file = new File(filePath); |
| 27 | + ByteSource byteSource = com.google.common.io.Files.asByteSource(file); |
| 28 | + HashCode hc = byteSource.hash(Hashing.md5()); |
| 29 | + return hc.toString(); |
| 30 | + } |
| 31 | + |
| 32 | + public static String genWithMessageDigest(String filePath) throws IOException, NoSuchAlgorithmException { |
| 33 | + byte[] data = Files.readAllBytes(Paths.get(filePath)); |
| 34 | + byte[] hash = MessageDigest.getInstance("MD5").digest(data); |
| 35 | + return new BigInteger(1, hash).toString(16); |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { |
| 39 | + String filePath = "D:\\temp.txt"; |
| 40 | + System.out.println(genWithApacheCommons(filePath)); |
| 41 | + System.out.println(genWithMessageDigest(filePath)); |
| 42 | + System.out.println(genWithGuava(filePath)); |
| 43 | + } |
| 44 | +} |
0 commit comments