SplitInputStream extends InputStream { @Override public int read() throws IOException { if (this.pos == this.boundary.length) { return -1; } final int next = this.in.read(); if (next == -1) { return -1; } if (next == this.boundary[this.pos]) { if (++this.pos == this.boundary.length) { this.prefix = new ByteArrayInputStream(new byte[0], 0, 0); } } else { this.pos = 0; } return next; } SplitInputStream(InputStream in, byte[] boundary); @Override int read(); @Override int read(byte[] b, int off, int len); InputStream next();  }
@Test public void testRead() throws IOException { final byte[] data = new byte[] {'a', 'b', '\r', '\n', '\r', '\n', 'c', 'd'}; @SuppressWarnings("resource") final SplitInputStream sin = new SplitInputStream(new ByteArrayInputStream(data), new byte[] {'\r', '\n'}); assertEquals('a', sin.read()); assertEquals('b', sin.read()); assertEquals('\r', sin.read()); assertEquals('\n', sin.read()); assertEquals(-1, sin.read()); assertEquals(-1, sin.read()); final InputStream in = sin.next(); assertEquals('\r', in.read()); assertEquals('\n', in.read()); assertEquals('c', in.read()); assertEquals('d', in.read()); assertEquals(-1, in.read()); }