我正在尝试尽快获取文件的哈希值。我有一个程序,可以对大量数据(100GB+)进行哈希处理,这些数据由随机文件大小(每个文件从几KB到5GB+)组成,跨少量文件到数十万个文件。
该程序必须支持所有 Java 支持的算法(MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512)。
目前我使用:
/**
* Gets Hash of file.
*
* @param file String path + filename of file to get hash.
* @param hashAlgo Hash algorithm to use. <br/>
* Supported algorithms are: <br/>
* MD2, MD5 <br/>
* SHA-1 <br/>
* SHA-256, SHA-384, SHA-512
* @return String value of hash. (Variable length dependent on hash algorithm used)
* @throws IOException If file is invalid.
* @throws HashTypeException If no supported or valid hash algorithm was found.
*/
public String getHash(String file, String hashAlgo) throws IOException, HashTypeException {
StringBuffer hexString = null;
try {
MessageDigest md = MessageDigest.getInstance(validateHashType(hashAlgo));
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
fis.close();
byte[] mdbytes = md.digest();
hexString = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
hexString.append(Integer.toHexString((0xFF & mdbytes[i])));
}
return hexString.toString();
} catch (NoSuchAlgorithmException | HashTypeException e) {
throw new HashTypeException("Unsuppored Hash Algorithm.", e);
}
}
是否有更优化的方法来获取文件哈希?我正在寻找极致的性能,但不确定我是否已经采取了最好的方法。
我看到了许多潜在的性能改进。一是使用StringBuilder
代替StringBuffer
;它与源兼容,但性能更高,因为它是不同步的。第二个(更重要的)是使用FileChannel
和java.nio
API 代替FileInputStream
——或者至少,包裹住FileInputStream
in a BufferedInputStream
优化 I/O。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)