前言
给客户交付的文件,客户需要验证md5值,客户java语言,记录下实现过程,很简单。文章来源:https://www.toymoban.com/news/detail-797560.html
代码
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMD5Generator {
public static String generateMD5(String filePath) {
try {
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[8192];
try (FileInputStream fis = new FileInputStream(filePath)) {
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
md5Digest.update(buffer, 0, bytesRead);
}
}
byte[] md5Bytes = md5Digest.digest();
// Convert the byte to hex format
StringBuilder result = new StringBuilder();
for (byte md5Byte : md5Bytes) {
result.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1));
}
return result.toString();
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace(); // Handle the exception according to your requirements
return null;
}
}
public static void main(String[] args) {
String filePath = "path/to/your/file.txt"; // Replace with the actual file path
String md5 = generateMD5(filePath);
if (md5 != null) {
System.out.println("MD5: " + md5);
} else {
System.out.println("Error generating MD5");
}
}
}
请替换 path/to/your/file.txt 为你实际文件的路径。这个 Java 代码会读取文件内容并生成相应的 MD5 值。文章来源地址https://www.toymoban.com/news/detail-797560.html
到了这里,关于java获取文件md5值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!