2 * © 2008 INA Service GmbH
4 package net.pterodactylus.util.io;
6 import java.io.FilterInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
11 * A wrapper around an {@link InputStream} that only supplies a limit number of
12 * bytes from the underlying input stream.
14 * @author <a href="mailto:dr@ina-germany.de">David Roden</a>
17 public class LimitedInputStream extends FilterInputStream {
19 /** The remaining number of bytes that can be read. */
20 private long remaining;
23 * Creates a new LimitedInputStream that supplies at most
24 * <code>length</code> bytes from the given input stream.
29 * The number of bytes to read
31 public LimitedInputStream(InputStream inputStream, long length) {
37 * @see java.io.FilterInputStream#available()
40 public synchronized int available() throws IOException {
41 return (int) Math.min(super.available(), Math.min(Integer.MAX_VALUE, remaining));
45 * @see java.io.FilterInputStream#read()
48 public synchronized int read() throws IOException {
58 * @see java.io.FilterInputStream#read(byte[], int, int)
61 public synchronized int read(byte[] b, int off, int len) throws IOException {
65 int toCopy = (int) Math.min(len, Math.min(remaining, Integer.MAX_VALUE));
66 int read = super.read(b, off, toCopy);
72 * @see java.io.FilterInputStream#skip(long)
75 public synchronized long skip(long n) throws IOException {
79 long skipped = super.skip(Math.min(n, remaining));
87 * This method does nothing, as {@link #mark(int)} and {@link #reset()} are
90 * @see java.io.FilterInputStream#mark(int)
93 public void mark(int readlimit) {
100 * @see java.io.FilterInputStream#markSupported()
101 * @return <code>false</code>
104 public boolean markSupported() {
111 * This method does nothing, as {@link #mark(int)} and {@link #reset()} are
114 * @see java.io.FilterInputStream#reset()
117 public void reset() throws IOException {
122 * Consumes the input stream, i.e. read all bytes until the limit is
125 * @throws IOException
126 * if an I/O error occurs
128 public void consume() throws IOException {
129 while (remaining > 0) {