GnawedInputStream extends InputStream { @Override public int read() throws IOException { if (this.gnawedIndex < this.gnawedLength) { return this.gnawedPart[this.gnawedIndex++]; } return this.gnawedStream.read(); } GnawedInputStream(byte[] gnawedPart, int gnawedLength, InputStream gnawedStream); @Override int read(); @Override int read(byte[] b, int off, int len); @Override void close(); @Override int available(); @Override boolean markSupported(); @Override synchronized void mark(int i); @Override synchronized void reset();  }
@Test public void testWorksIfStreamIsNotGnawed() throws IOException { BufferedReader originalReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/leaves-of-grass.txt"))); InputStream stream = getClass().getResourceAsStream("/leaves-of-grass.txt"); byte[] buf = new byte[0]; int read = stream.read(buf); GnawedInputStream gnawedInputStream = new GnawedInputStream(buf, read, stream); BufferedReader testReader = new BufferedReader(new InputStreamReader(gnawedInputStream)); String originalLine; while ((originalLine = originalReader.readLine()) != null) { Assert.assertEquals(originalLine, testReader.readLine()); } Assert.assertEquals(null, testReader.readLine()); }
@Test public void testWorksIfStreamIsGnawed() throws IOException { BufferedReader originalReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/leaves-of-grass.txt"))); InputStream stream = getClass().getResourceAsStream("/leaves-of-grass.txt"); byte[] buf = new byte[100000]; int read = stream.read(buf, 0, 99999); GnawedInputStream gnawedInputStream = new GnawedInputStream(buf, read, stream); BufferedReader testReader = new BufferedReader(new InputStreamReader(gnawedInputStream)); String originalLine; while ((originalLine = originalReader.readLine()) != null) { Assert.assertEquals(originalLine, testReader.readLine()); } Assert.assertEquals(null, testReader.readLine()); }
@Test public void testWorksIfStreamIsCompletelyConsumed() throws IOException { BufferedReader originalReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/leaves-of-grass.txt"))); InputStream stream = getClass().getResourceAsStream("/leaves-of-grass.txt"); byte[] buf = new byte[10000000]; int read = stream.read(buf); GnawedInputStream gnawedInputStream = new GnawedInputStream(buf, read, stream); BufferedReader testReader = new BufferedReader(new InputStreamReader(gnawedInputStream)); String originalLine; while ((originalLine = originalReader.readLine()) != null) { Assert.assertEquals(originalLine, testReader.readLine()); } Assert.assertEquals(null, testReader.readLine()); }