基本信息
源码名称:Java计算文件MD5值(支持大文件)
源码大小:0.99KB
文件格式:.zip
开发语言:Java
更新时间:2019-10-17
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CalcMD5 {
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
public static void main(String[] args) {
long beginTime = System.currentTimeMillis();
File file = new File("C:/Users/Administrator/Downloads/OpenCVSharp-Samples.rar");
String md5 = calcMD5(file);
long endTime = System.currentTimeMillis();
System.out.println("MD5:" md5 "\n 耗时:" ((endTime - beginTime) / 1000) "s");
}
/**
* 计算文件 MD5
* @param file
* @return 返回文件的md5字符串,如果计算过程中任务的状态变为取消或暂停,返回null, 如果有其他异常,返回空字符串
*/
protected static String calcMD5(File file) {
try (InputStream stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] buf = new byte[8192];
int len;
while ((len = stream.read(buf)) > 0) {
digest.update(buf, 0, len);
}
return toHexString(digest.digest());
} catch (IOException e) {
e.printStackTrace();
return "";
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
public static String toHexString(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString().toLowerCase();
}
}