CappedInputStream extends FilterInputStream { void exhaustAndClose() throws IOException { lock.runChecked(() -> { long toSkip = capacity - readSoFar; assert toSkip >= 0; while (toSkip > 0) { toSkip -= skip(toSkip); } close(); }); } CappedInputStream(@Nonnull InputStream in, long capacity); @Override int read(); @Override int available(); @Override int read(@Nonnull byte[] b, int off, int len); @Override void close(); @Override boolean markSupported(); @Override synchronized void reset(); @Override synchronized void mark(int readlimit);  }
@Test public void exhaustAndClose() throws IOException { TestInputStream countingStream = new TestInputStream(testStream); CappedInputStream cappedStream = new CappedInputStream(countingStream, 50); cappedStream.exhaustAndClose(); assertThat(countingStream.getSkipCount()).isEqualTo(50); assertThat(countingStream.getReadCount()).isEqualTo(0); assertThat(cappedStream.available()).isEqualTo(0); assertThatExceptionOfType(IOException.class).isThrownBy(cappedStream::read); }