sclass BoundedInputStream extends InputStream { InputStream in; long max, pos; long mark = -1; *(InputStream *in, long *max) {} *(long *max, InputStream *in) {} public int read() throws IOException { if (max >= 0 && pos >= max) ret -1; int result = in.read(); pos++; ret result; } public int read(final byte[] b) throws IOException { ret read(b, 0, b.length); } public int read(final byte[] b, final int off, final int len) throws IOException { if (max>=0 && pos>=max) ret -1; long maxRead = max>=0 ? Math.min(len, max-pos) : len; int bytesRead = in.read(b, off, (int)maxRead); if (bytesRead < 0) ret -1; pos+=bytesRead; return bytesRead; } public long skip(final long n) throws IOException { long toSkip = max>=0 ? Math.min(n, max-pos) : n; long skippedBytes = in.skip(toSkip); pos+=skippedBytes; return skippedBytes; } public int available() throws IOException { if (max>=0 && pos>=max) ret 0; ret in.available(); } public void close() throws IOException { in.close(); } public synchronized void reset() throws IOException { in.reset(); pos = mark; } public synchronized void mark(final int readlimit) { in.mark(readlimit); mark = pos; } public bool markSupported() { ret in.markSupported(); } }