作者:宝宝717917 | 来源:互联网 | 2022-12-13 19:24
File类的hashCode()只是Computesahashcodeforthisabstractpathname。即计算文件的相对路径,如:"F:\\TMLab\\baidu
File类的hashCode()只是Computes a hash code for this abstractpathname。
即计算文件的相对路径,如:
"F:\\TMLab\\baiduwenku\\待下载的文档\\download_list0.txt"的hash值,并不是文件本身的hash值。
测试代码:
String filePath = "F:\\TMLab\\baiduwenku\\待下载的文档\\download_list0.txt";
File file1 = new File(filePath);
File file2 = new File(filePath);
if (file1.hashCode() == file2.hashCode()) {
System.out.println("The same file!");
}
结果:"The same file!"
要计算文件本身的hash值,用MessageDigest类,需要读入文件的byte。一篇例文:
http://hi.baidu.com/black_zhu/item/04472b099819e8e1f55ba6da
hashType的值:"MD5","SHA1","SHA-256","SHA-384","SHA-512"
private static String getHash(String fileName, String hashType)
throws Exception
{
InputStream fis = new FileInputStream(fileName);
byte buffer[] = new byte[1024];
MessageDigest md5 = MessageDigest.getInstance(hashType);
for(int numRead = 0; (numRead = fis.read(buffer)) > 0;)
{
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
}