gpt4 book ai didi

java - 获取文件哈希性能/优化

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:26 25 4
gpt4 key购买 nike

我正在尝试尽快获取文件的哈希值。我有一个程序可以散列大量数据 (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;它与源代码兼容但性能更高,因为它是不同步的。第二个(更重要的)是使用 FileChanneljava.nio API 而不是 FileInputStream —— 或者至少,包装BufferedInputStream 中的 FileInputStream 以优化 I/O。

关于java - 获取文件哈希性能/优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15932821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com