2 * Sonitus - RememberingInputStream.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sonitus.io;
20 import java.io.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.FilterInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.SequenceInputStream;
28 * Wrapper around an {@link InputStream} that remembers all bytes that have been
29 * read from the wrapped input stream. The remembered bytes can be retrieved
30 * from this stream as another input stream, suitable for use with {@link
31 * java.io.SequenceInputStream}.
33 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
35 public class RememberingInputStream extends FilterInputStream {
37 /** The buffer for the read bytes. */
38 private final ByteArrayOutputStream rememberBuffer = new ByteArrayOutputStream();
41 * Creates a new remembering input stream.
44 * The input stream to remember
46 public RememberingInputStream(InputStream inputStream) {
55 * Returns an input stream that repeats the originally wrapped stream,
56 * including all bytes that have already been read.
58 * @return A new input stream with the original content
60 public InputStream remembered() {
61 return new SequenceInputStream(new ByteArrayInputStream(rememberBuffer.toByteArray()), in);
65 // INPUTSTREAM METHODS
69 public boolean markSupported() {
74 public int read() throws IOException {
75 int read = super.read();
77 rememberBuffer.write(read);
83 public int read(byte[] bytes) throws IOException {
84 return read(bytes, 0, bytes.length);
88 public int read(byte[] bytes, int offset, int length) throws IOException {
89 int read = super.read(bytes, offset, length);
91 rememberBuffer.write(bytes, offset, read);
97 public synchronized void reset() throws IOException {
98 throw new IOException("mark()/reset() not supported");
102 * {@inheritDoc} <p> This method disallows seeking and always returns {@code
106 public long skip(long l) throws IOException {