3 回答
![?](http://img1.sycdn.imooc.com/533e4c9c0001975102200220-100-100.jpg)
TA贡献1765条经验 获得超5个赞
你想要做的是从ByteStreams.copy(input, Funnels.asOutputStream(hasher))
哪里hasher
获得例如Hashing.sha256().newHasher()
。然后,调用hasher.hash()
以获取结果HashCode
。
![?](http://img1.sycdn.imooc.com/5923e28b0001bb7201000100-100-100.jpg)
TA贡献1725条经验 获得超7个赞
如果要计算其包含的字节的哈希值,则必须读取 InputStream。首先将 InputSteam 读取到 byte[]。
使用 Guava 使用 ByteStreams:
InputStream in = ...;
byte[] bytes = ByteStreams.toByteArray(in);
另一种流行的方法是使用Commons IO:
InputStream in = ...;
byte[] bytes = IOUtils.toByteArray(in);
然后你可以在字节数组上调用 Arrays.hashCode() :
int hash = java.util.Arrays.hashCode(bytes);
但是,您可能会考虑使用 SHA256 作为您的哈希函数,因为您不太可能发生冲突:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] sha256Hash = digest.digest(bytes);
如果您不想将整个流读取到内存字节数组中,则可以在其他人读取 InputStream 时计算哈希。例如,您可能希望将 InputStream 流式传输到磁盘到数据库中。Guava 提供了一个封装了 InputStream 的类,它为您执行此操作 HashingInputStream:
首先用 HashinInputStream 包装你的 InputStream
HashingInputStream hin = new HashingInputStream(Hashing.sha256(), in);
然后让 HashingInputStream 以您喜欢的任何方式读取
while(hin.read() != -1);
然后从 HashingInputStream 中获取哈希
byte[] sha256Hash = hin.hash().asBytes();
![?](http://img1.sycdn.imooc.com/5333a207000118af02200220-100-100.jpg)
TA贡献2021条经验 获得超8个赞
我建议使用 Files.asByteSource(fileSource.getFile()).hash(hashFunction).padToLong()
添加回答
举报