Fast way to compare inputstreams

后端 未结 4 2064

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) thr         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-05 05:51

    why not simply wrap both streams at the very beginning of your method:

    i1 = new BufferedInputStream(i1);
    i2 = new BufferedInputStream(i2);
    

    Alternatively, you could simply try reading both streams into a buffer:

    public static boolean equals(InputStream i1, InputStream i2, int buf) throws IOException {
        try {
            // do the compare
            while (true) {
                byte[] b1 = new byte[buf];
                byte[] b2 = new byte[buf];
    
                int length = i1.read(b1);
                if (length == -1) {
                    return i2.read(b2, 0, 1) == -1;
                }
    
                try {
                    StreamUtils.readFully(i2, b2, 0, length);
                } catch (EOFException e) {
                    // i2 is shorter than i1
                    return false;
                }
    
                if (!ArrayUtils.equals(b1, b2, 0, length)) {
                    return false;
                }
            }
        } finally {
            // simply close streams and ignore (log) exceptions
            StreamUtils.close(i1, i2);
        }
    }
    
    // StreamUtils.readFully(..) 
    public static void readFully(InputStream in, byte[] b, int off, int len) throws EOFException, IOException {
        while (len > 0) {
            int read = in.read(b, off, len);
            if (read == -1) {
                throw new EOFException();
            }
            off += read;
            len -= read;
        }
    }
    
    // ArrayUtils.equals(..)
    public static boolean equals(byte[] a, byte[] a2, int off, int len) {
        if (off < 0 || len < 0 || len > a.length - off || len > a2.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return true;
        }
    
        if (a == a2) {
            return true;
        }
        if (a == null || a2 == null) {
            return false;
        }
    
        for (int i = off; i < off + len; i++) {
            if (a[i] != a2[i]) {
                return false;
            }
        }
    
        return true;
    }
    

    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:

    
      at.molindo
      molindo-utils
      1.0-SNAPSHOT
    
    

提交回复
热议问题