在Java中,獲取文件的MD5值的方法主要有以下幾種:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMD5 {
public static String getFileMD5(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fis.read(buffer)) != -1) {
md5Digest.update(buffer, 0, length);
}
fis.close();
byte[] digest = md5Digest.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
import org.apache.commons.codec.digest.DigestUtils;
public class FileMD5 {
public static String getFileMD5(File file) throws IOException {
return DigestUtils.md5Hex(new FileInputStream(file));
}
}
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMD5 {
public static String getFileMD5(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
Path filePath = Paths.get(file.getAbsolutePath());
byte[] fileBytes = Files.readAllBytes(filePath);
byte[] digest = md5Digest.digest(fileBytes);
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
這些方法都可以獲取文件的MD5值,可以根據(jù)具體的需求選擇適合的方法。