I created a class that extends InputStream so that I can keep count of the number of bytes being read and throw an exception if it exceeds a max limit that I define.
Her
If LimitedSizeInputStream
extends InputStream
and wraps another stream, then @areus's solution is the best one.
An alternative approach would be to extend FilterInputStream
, like this:
public class LimitedSizeInputStream extends FilterInputStream
{
private final long maxSize;
private long total;
public LimitedSizeInputStream(InputStream original, long maxSize)
{
super(original);
this.original = original;
this.maxSize = maxSize;
}
// use 'this.in' instead of 'this.original'
// at least one of the 'read' methods needs to be overridden.
}
Note that FilterInputStream
provides default implementations of the API methods that may prove useful.
The javadoc provides details of what the default method implementations do.
The try-with-resources only closes the declared resource. So will only close metadataStream
.
You should implement the close
method in LimitedSizeInputStream
to close the original stream.
@Override
public void close() throws IOException {
original.close();
}