Java 字节数组中无法容纳文件
Cannot fit file in Java Byte Array
我正在编写 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;
}
我 运行 此代码用于大小为 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)
...
我可以在这里使用另一种数据结构吗?或者我应该寻找另一种策略将文件提供给哈希函数吗?
Guava 的 HashFunctions 不知道如何处理 ByteSources。但是 ByteSources 知道如何处理 HashFunctions。就那样做。
HashCode hsCode = Files.asByteSource(file).hash(hc);
我正在编写 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;
}
我 运行 此代码用于大小为 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)
...
我可以在这里使用另一种数据结构吗?或者我应该寻找另一种策略将文件提供给哈希函数吗?
Guava 的 HashFunctions 不知道如何处理 ByteSources。但是 ByteSources 知道如何处理 HashFunctions。就那样做。
HashCode hsCode = Files.asByteSource(file).hash(hc);