【问题标题】:Cannot fit file in Java Byte Array无法将文件放入 Java 字节数组
【发布时间】:2018-12-11 08:02:22
【问题描述】:

我正在编写为给定文件生成校验和的 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)
    ...

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

【问题讨论】:

标签: java arrays hash guava checksum


【解决方案1】:

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

HashCode hsCode = Files.asByteSource(file).hash(hc);

【讨论】:

  • 这行得通。对于其他人,这里提到的“文件”不是“java.nio.file.Files”。它是“com.google.common.io.Files”。
猜你喜欢
  • 2020-05-05
  • 2015-09-04
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 2021-12-30
  • 2014-04-10
相关资源
最近更新 更多