要獲取文件的MD5值,可以使用Java的MessageDigest類。以下是一個示例代碼:
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMD5Checksum {
public static String getFileMD5(String filePath) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(filePath);
DigestInputStream dis = new DigestInputStream(fis, md);
byte[] buffer = new byte[1024];
while (dis.read(buffer) != -1) {
// 讀取文件內容時會自動更新MD5值
}
dis.close();
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String filePath = "path/to/file";
String md5 = getFileMD5(filePath);
System.out.println("File MD5: " + md5);
}
}
請將代碼中的filePath
替換為實際文件路徑。運行代碼后,將會打印出文件的MD5值。