BAEL-5615-gen-md5-checksum-of-file (#12668)

Co-authored-by: tienvn4 <tienvn4@ghtk.co>
This commit is contained in:
vunamtien 2022-08-30 20:51:01 +07:00 committed by GitHub
parent 78b7c6dcf8
commit 72daf77666
2 changed files with 54 additions and 0 deletions

View File

@ -32,6 +32,16 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,44 @@
package com.baeldung.md5checksum;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteSource;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5ChecksumGenerator {
public static String genWithApacheCommons(String filePath) throws IOException {
try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
return DigestUtils.md5Hex(is);
}
}
public static String genWithGuava(String filePath) throws IOException {
File file = new File(filePath);
ByteSource byteSource = com.google.common.io.Files.asByteSource(file);
HashCode hc = byteSource.hash(Hashing.md5());
return hc.toString();
}
public static String genWithMessageDigest(String filePath) throws IOException, NoSuchAlgorithmException {
byte[] data = Files.readAllBytes(Paths.get(filePath));
byte[] hash = MessageDigest.getInstance("MD5").digest(data);
return new BigInteger(1, hash).toString(16);
}
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
String filePath = "D:\\temp.txt";
System.out.println(genWithApacheCommons(filePath));
System.out.println(genWithMessageDigest(filePath));
System.out.println(genWithGuava(filePath));
}
}