Java代码如何获取一个文件的MD5值呢?
下文笔者讲述使用java代码获取一个文件的MD5值的方法分享,如下所示
文件MD5值计算的实现思路:
1.将文件读取为一个字节数组
2.声明MD5对象
3.计算出字节数组对应的MD5值即可
例:计算文件的MD5值
/**
* 计算文件MD5
* @return 文件MD5
*/
public static String getMd5ByFile(String path) throws FileNotFoundException {
File file = new File(path);
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 (Exception e) {
return null;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
return null;
}
}
}
return value;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


