比较输入流的快速方法
我有一个问题,我需要快速比较两个输入流。
今天我有一个这样的功能:
private boolean isEqual(InputStream i1, InputStream i2) throws IOException {
try {
// do the compare
while (true) {
int fr = i1.read();
int tr = i2.read();
if (fr != tr)
return false;
if (fr == -1)
return true;
}
} finally {
if (i1 != null)
i1.close();
if (i2 != null)
i2.close();
}
}
但是它真的很慢。我想使用缓冲读取,但还没有想出一个好的方法。
一些额外的东西使它变得更加困难:
- 我不想将一个输入流读入内存(整个)
- 我不想使用第三方库
我需要一个实用的解决方案 - 代码! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
到目前为止,我最喜欢的是使用 org.apache.commons.io.IOUtils 帮助器类rel="noreferrer">Apache Commons IO 库:
By far my favorite is to use the
org.apache.commons.io.IOUtils
helper class from the Apache Commons IO library:像这样的事情可能会做:
Something like this may do:
使用缓冲读取只需用 BufferedInputStreams 包装 InputStreams 即可。但是,一次读取大块可能会获得最佳性能。
Using buffered reads is just a matter of wrapping the InputStreams with BufferedInputStreams. However you are likely to get the best performance reading large blocks at a time.
为什么不简单地将两个流包装在方法的最开始处:
或者,您可以简单地尝试将两个流读入缓冲区:
编辑:我现在已经修复了我的实现。这就是没有 DataInputStream 或 NIO 的情况。代码可在 GitHub 或 Sonatype 的 OSS 快照存储库 Maven:
why not simply wrap both streams at the very beginning of your method:
Alternatively, you could simply try reading both streams into a buffer:
EDIT: I've fixed my implementation now. That's how it looks like without DataInputStream or NIO. Code is available at GitHub or from Sonatype's OSS Snapshot Repository Maven: