我想使用Java来获得文件的MD5校验和。我真的很惊讶,但我还没有找到任何东西,显示如何获得一个文件的MD5校验和。
这是怎么做到的?
我想使用Java来获得文件的MD5校验和。我真的很惊讶,但我还没有找到任何东西,显示如何获得一个文件的MD5校验和。
这是怎么做到的?
当前回答
使用Java 7的简单方法,没有第三方库
String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();
如果你需要打印这个字节数组。使用方法如下
System.out.println(Arrays.toString(digest));
如果你需要十六进制字符串出这个摘要。使用方法如下
String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);
其中DatatypeConverter是javax.xml.bind.DatatypeConverter
其他回答
谷歌guava提供了一个新的API。找到下面的一个:
public static HashCode hash(File file,
HashFunction hashFunction)
throws IOException
Computes the hash code of the file using hashFunction.
Parameters:
file - the file to read
hashFunction - the hash function to use to hash the data
Returns:
the HashCode of all of the bytes in the file
Throws:
IOException - if an I/O error occurs
Since:
12.0
好的。对于那些已经有Spring和Apache Commons依赖关系或计划添加它的人,我必须添加。
DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
对于和Apache共享的唯一选项(credit @duleshi):
DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
希望这能帮助到一些人。
在Real的Java-How-to中有一个使用MessageDigest类的例子。
请查看该页面中使用CRC32和SHA-1的示例。
import java.io.*;
import java.security.MessageDigest;
public class MD5Checksum {
public static byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
// see this How-to for a faster way to convert
// a byte array to a HEX string
public static String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static void main(String args[]) {
try {
System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
// output :
// 0bb2827c5eacf570b6064e24e0e6653b
// ref :
// http://www.apache.org/dist/
// tomcat/tomcat-5/v5.5.17/bin
// /apache-tomcat-5.5.17.exe.MD5
// 0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
}
catch (Exception e) {
e.printStackTrace();
}
}
}
使用Java 7的简单方法,没有第三方库
String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();
如果你需要打印这个字节数组。使用方法如下
System.out.println(Arrays.toString(digest));
如果你需要十六进制字符串出这个摘要。使用方法如下
String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);
其中DatatypeConverter是javax.xml.bind.DatatypeConverter
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));