LimitInputStream extends FilterInputStream { @Override public int read() throws IOException { if (left == 0) { return -1; } int result = in.read(); if (result != -1) { --left; } return result; } LimitInputStream(InputStream in, long limit); @Override int available(); @Override synchronized void mark(int readLimit); @Override int read(); @Override int read(byte[] b, int off, int len); @Override synchronized void reset(); @Override long skip(long n);  }
@Test public void testRead() throws IOException { try (LimitInputStream limitInputStream = new LimitInputStream(new RandomInputStream(), 0)) { assertEquals("Reading byte after reaching limit should return -1", -1, limitInputStream.read()); } try (LimitInputStream limitInputStream = new LimitInputStream(new RandomInputStream(), 4)) { assertEquals("Incorrect byte returned", new Random(0).nextInt(), limitInputStream.read()); } }
@Test public void testReadBytes() throws IOException { try (LimitInputStream limitInputStream = new LimitInputStream(new RandomInputStream(), 128)) { Random r = new Random(0); byte[] data = new byte[4]; byte[] expected = { (byte) r.nextInt(), (byte) r.nextInt(), (byte) r.nextInt(), (byte) r.nextInt() }; limitInputStream.read(data, 0, 4); assertArrayEquals("Incorrect bytes returned", expected, data); } }