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

LGPL

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.

Exception

Parameter Description
IOException Signals that an I/O exception has occurred.

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: LGPL 

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

public class Main {
    /** The Constant BUFFER_SIZE. */
    private static final int BUFFER_SIZE = 1024;

    /**/*from w  w  w  .ja  v  a  2s  .  c  o  m*/
     * 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
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static boolean binaryStreamEquals(InputStream left, InputStream right) throws IOException {
        try (InputStream first = left; InputStream second = right) {
            if (first == second) { // NOSONAR
                // The same stream! This is pretty pointless, but they are
                // equal, nevertheless.
                return true;
            }
            return compareStreamsInternal(first, second);
        }
    }

    private static boolean compareStreamsInternal(InputStream first, InputStream second) throws IOException {
        byte[] leftBuffer = new byte[BUFFER_SIZE];
        byte[] rightBuffer = new byte[BUFFER_SIZE];
        while (true) {
            int leftReadCount = first.read(leftBuffer);
            int rightReadCount = second.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
    }
}

Related

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