java获取文件md5值
时间: 2024-05-15 12:08:27 浏览: 100
java 获取文件MD5值
Java中获取文件MD5值的方法有多种。其中,可以使用Apache的commons-codec库、Junit测试框架或Java原生的MessageDigest类来实现。
方法一:使用Apache的commons-codec库
```java
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.FileInputStream;
File file = new File("d:/test1.jpg");
String md5 = DigestUtils.md5Hex(new FileInputStream(file));
System.out.println(md5);
```
方法二:使用Junit测试框架
```java
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
@Test
public void test_getFileMD5() throws Exception{
String filepath = "D:\\download\\3_尚学堂_UML概览.avi";
String md5_1 = SystemUtil.getFileMD5(filepath);
System.out.println(md5_1);
byte[] bytes = FileUtils.readFileToByteArray(new File(filepath));
byte[] md5 = SystemUtil.encryptMD5(bytes);
String md5_2 = SystemUtil.toHexString(md5);
System.out.println(md5_2);
Assert.assertEquals(md5_1, md5_2);
}
```
方法三:使用Java原生的MessageDigest类
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
File file = new File("d:/test1.jpg");
String value = null;
FileInputStream in = new FileInputStream(file);
try {
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(value);
```
阅读全文