Java InputStream Compare binaryStreamEquals(InputStream left, InputStream right)

Here you can find the source of binaryStreamEquals(InputStream left, InputStream right)

Description

Performs a byte-level comparison between two streams.

License

Apache License

Parameter

Parameter Description
left the left stream. This is closed at the end of the operation.
right an right stream. This is closed at the end of the operation.

Return

Returns true if the streams are identical to the last byte

Declaration

public static boolean binaryStreamEquals(InputStream left, InputStream right) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static final int BUFFER_SIZE = 1024;

    /**//from   w w  w.j  a v  a2  s. c  om
     * Performs a byte-level comparison between two streams.
     * 
     * @param left         the left stream.  This is closed at the end of the operation.
     * @param right        an right stream.  This is closed at the end of the operation.
     * @return             Returns <tt>true</tt> if the streams are identical to the last byte
     */
    public static boolean binaryStreamEquals(InputStream left, InputStream right) throws IOException {
        try {
            if (left == right) {
                // The same stream!  This is pretty pointless, but they are equal, nevertheless.
                return true;
            }

            byte[] leftBuffer = new byte[BUFFER_SIZE];
            byte[] rightBuffer = new byte[BUFFER_SIZE];
            while (true) {
                int leftReadCount = left.read(leftBuffer);
                int rightReadCount = right.read(rightBuffer);
                if (leftReadCount != rightReadCount) {
                    // One stream ended before the other
                    return false;
                } else if (leftReadCount == -1) {
                    // Both streams ended without any differences found
                    return true;
                }
                for (int i = 0; i < leftReadCount; i++) {
                    if (leftBuffer[i] != rightBuffer[i]) {
                        // We found a byte difference
                        return false;
                    }
                }
            }
            // The only exits with 'return' statements, so there is no need for any code here
        } finally {
            try {
                left.close();
            } catch (Throwable e) {
            }
            try {
                right.close();
            } catch (Throwable e) {
            }
        }
    }
}

Related

  1. binaryStreamEquals(InputStream left, InputStream right)
  2. inputStreamEquals(InputStream is1, InputStream is2)