You can compare the contents from two InputStream
objects by reading just a buffer at a time. You'll need to read data as and when you "run out" from each stream, noting that you when you call read
you may not end up actually reading a full buffer.
The two streams are equal if each byte-by-byte comparison from the buffers is equal and the streams run out of data at the same time. I suspect the code may be slightly fiddly, but it shouldn't be too bad.
In fact, for simpler code, if you wrap each InputStream
in a BufferedInputStream
, you could probably just compare byte-by-byte (calling the parameterless read()
method on each iteration) without losing too much performance:
public boolean equals(InputStream x, InputStream y)
{
// TODO: Only wrap them if they're not already buffered
x = new BufferedInputStream(x);
y = new BufferedInputStream(y);
while (true)
{
int xValue = x.read();
int yValue = y.read();
if (xValue != yValue)
{
return false;
}
if (xValue == -1)
{
// Reached the end of both streams at the same time
return true;
}
}
}