无法在Java字节数组中使用文件

Que*_*ger 1 java arrays hash checksum guava

我正在研究为给定文件生成校验和的Java代码.我正在使用Gogole的Guava库进行散列.这是代码 -

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

private HashCode doHash(File file) throws IOException {
    HashFunction hc = Hashing.murmur3_128();
    HashCode hsCode = hc.newHasher().putBytes(com.google.common.io.Files.asByteSource(file).read()).hash();
    return hsCode;
}
Run Code Online (Sandbox Code Playgroud)

我运行此代码的文件大小为2.8GB.它抛出以下错误 -

Exception in thread "main" java.lang.OutOfMemoryError: 2945332859 bytes is too large to fit in a byte array
    at com.google.common.io.ByteStreams.toByteArray(ByteStreams.java:232)
    at com.google.common.io.Files$FileByteSource.read(Files.java:154)
    ...
Run Code Online (Sandbox Code Playgroud)

我可以在这里使用其他数据结构吗?或者我应该寻找另一种策略来将文件提供给哈希函数?

kum*_*ana 8

Guava的HashFunctions不知道如何处理ByteSources.但是ByteSources知道如何处理HashFunctions.就这样做吧.

HashCode hsCode = Files.asByteSource(file).hash(hc);
Run Code Online (Sandbox Code Playgroud)

  • 这很有效.对于其他人,这里提到的'文件'不是'java.nio.file.Files'.这是'com.google.common.io.Files'. (2认同)