写一个java函数传入File file读取该file对象存入byte digest再用 String hash = DatatypeConverterprintHexBinarydigest;最后返回该String
可以使用以下代码实现:
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static String getFileHash(File file) {
try {
// 创建MessageDigest对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 创建文件输入流
FileInputStream fis = new FileInputStream(file);
// 创建一个byte数组用于存储读取的数据
byte[] buffer = new byte[8192];
int bytesRead;
// 循环读取文件内容并更新MessageDigest对象
while ((bytesRead = fis.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
// 关闭文件输入流
fis.close();
// 计算摘要
byte[] digest = md.digest();
// 转换为十六进制字符串
String hash = DatatypeConverter.printHexBinary(digest);
// 返回结果
return hash;
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
File file = new File("example.txt");
String hash = getFileHash(file);
System.out.println(hash);
}
}
在上述代码中,我们使用MessageDigest类来计算文件的摘要。首先,我们获取一个MD5算法的MessageDigest实例。然后,我们创建一个FileInputStream来读取文件的内容,并使用一个缓冲区来存储每次读取的数据。在读取文件内容的过程中,我们通过调用update方法来更新MessageDigest对象。最后,我们通过调用digest方法来计算出文件的摘要,并使用DatatypeConverter.printHexBinary方法将摘要转换为十六进制字符串。最终,我们返回该字符串作为函数的结果
原文地址: http://www.cveoy.top/t/topic/isss 著作权归作者所有。请勿转载和采集!