我正在寻找使用Java获取文件的MD5校验和。 我真的很惊讶,但是我找不到任何能显示如何获取文件的MD5校验和的东西。
怎么做?
#1楼
Guava现在提供了一个新的,一致的哈希API,它比JDK中提供的各种哈希API更友好。 请参阅哈希说明 。 对于文件,您可以轻松获得MD5和,CRC32(版本14.0+)或许多其他哈希值:
HashCode md5 = Files.hash(file, Hashing.md5());
byte[] md5Bytes = md5.asBytes();
String md5Hex = md5.toString();
HashCode crc32 = Files.hash(file, Hashing.crc32());
int crc32Int = crc32.asInt();
// the Checksum API returns a long, but it's padded with 0s for 32-bit CRC
// this is the value you would get if using that API directly
long checksumResult = crc32.padToLong();
#2楼
public static void main(String[] args) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}
或者您可能会获得更多信息http://www.asjava.com/core-java/java-md5-example/
#3楼
好。 我必须补充。 对于已经具有Spring和Apache Commons依赖项或计划添加它的人的一线实施:
DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
对于和仅Apache Commons选项(credit @duleshi):
DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
希望这对某人有帮助。
#4楼
public String checksum(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er =
MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;