Skip to content

Commit faf5028

Browse files
vunamtientienvn4
andauthored
BAEL-5615-gen-md5-checksum-of-file (eugenp#12668)
Co-authored-by: tienvn4 <tienvn4@ghtk.co>
1 parent 155567b commit faf5028

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

core-java-modules/core-java-io-4/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@
3232
<artifactId>log4j-over-slf4j</artifactId>
3333
<version>${org.slf4j.version}</version>
3434
</dependency>
35+
<dependency>
36+
<groupId>commons-codec</groupId>
37+
<artifactId>commons-codec</artifactId>
38+
<version>1.15</version>
39+
</dependency>
40+
<dependency>
41+
<groupId>com.google.guava</groupId>
42+
<artifactId>guava</artifactId>
43+
<version>31.1-jre</version>
44+
</dependency>
3545
</dependencies>
3646

3747
</project>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)