You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.0 KiB

package com.example.musicplayer.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* <pre>
* author : 残渊
* time : 2019/11/10
* desc : MD5加密工具
* </pre>
*/
public class MD5Util {
public static String getFileMD5(File file) {
// 如果文件为空或不存在,返回空字符串
if (file == null ||!file.exists()) return "";
FileInputStream in = null;
// 用于存储文件读取的数据
byte[] buffer = new byte[1024];
// 存储最终的 MD5 结果
StringBuilder res = new StringBuilder();
int len;
try {
// 获取 MD5 消息摘要对象
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
// 循环读取文件内容
while ((len = in.read(buffer))!= -1) {
// 更新消息摘要对象,分段读取文件数据
messageDigest.update(buffer, 0, len);
}
// 计算最终的 MD5 摘要
byte[] bytes = messageDigest.digest();
// 将 MD5 摘要的字节数组转换为 16 进制字符串
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length()!= 2) {
temp = "0" + temp;
}
res.append(temp);
}
// 返回最终的 MD5 字符串
return res.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null!= in) {
try {
// 关闭文件输入流
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return res.toString();
}
}