### Question:
TruncatedInputStream extends InputStream { @Override public int read() throws IOException { if (remained == 0) return -1; else { int res = is.read(); if (res >= 0) remained--; return res; } } TruncatedInputStream(InputStream is, int length); static InputStream createInstance(InputStream is, int contentLength); @Override int available(); @Override void mark(int readlimit); @Override boolean markSupported(); @Override void reset(); @Override void close(); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); @Override long skip(long n);  }### Answer:
@Test public void testSingleCharacterRead() throws Exception { InputStream is = new ByteArrayInputStream(new byte[] {1, 0, 2, 3, 4, 5, 6}); InputStream tr = new TruncatedInputStream(is, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = tr.read()) != -1) { baos.write(b); } assertArrayEquals(new byte[] {1, 0, 2}, baos.toByteArray()); }
@Test public void testWholeBufferRead() throws Exception { InputStream is = new ByteArrayInputStream(new byte[] {1, 2, 0, 3, 4, 5, 6}); InputStream tr = new TruncatedInputStream(is, 4); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[2]; int len; while ((len = tr.read(buf)) != -1) baos.write(buf, 0, len); assertArrayEquals(new byte[] {1, 2, 0, 3}, baos.toByteArray()); }
@Test public void testBufferSegmentRead() throws Exception { InputStream is = new ByteArrayInputStream(new byte[] {1, 0, 2, 3, 4, 5, 6}); InputStream tr = new TruncatedInputStream(is, 4); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[4]; int len; while ((len = tr.read(buf, 2, 2)) != -1) baos.write(buf, 2, len); assertArrayEquals(new byte[] {1, 0, 2, 3}, baos.toByteArray()); }