比较输入流的快速方法 [英] Fast way to compare inputstreams

查看:76
本文介绍了比较输入流的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我需要快速比较两个输入流。

I have a problem, I need to compare two inputstreams fast.

今天我有一个像这样的函数:

Today I have a function like this:

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();
    }
}

但这确实很慢。我想使用缓冲读取,但并没有提出一种好的方法。

But it's really slow. I want to use buffered reads but have not come up with a good way of doing it.

一些额外的东西使操作更加困难:

Some extra stuff that makes it harder:


  • 我不想将输入流之一读入内存(整个)

  • 我不想使用第三方库

我需要一个实用的解决方案-代码! :)

推荐答案

类似的事情可能会发生:

Something like this may do:

private static boolean isEqual(InputStream i1, InputStream i2)
        throws IOException {

    ReadableByteChannel ch1 = Channels.newChannel(i1);
    ReadableByteChannel ch2 = Channels.newChannel(i2);

    ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
    ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);

    try {
        while (true) {

            int n1 = ch1.read(buf1);
            int n2 = ch2.read(buf2);

            if (n1 == -1 || n2 == -1) return n1 == n2;

            buf1.flip();
            buf2.flip();

            for (int i = 0; i < Math.min(n1, n2); i++)
                if (buf1.get() != buf2.get())
                    return false;

            buf1.compact();
            buf2.compact();
        }

    } finally {
        if (i1 != null) i1.close();
        if (i2 != null) i2.close();
    }
}

这篇关于比较输入流的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆