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 {
44 return (int) Math.min(super.available(), Math.min(Integer.MAX_VALUE, remaining));
48 * @see java.io.FilterInputStream#read()
51 public synchronized int read() throws IOException {
61 * @see java.io.FilterInputStream#read(byte[], int, int)
64 public synchronized int read(byte[] b, int off, int len) throws IOException {
68 int toCopy = (int) Math.min(len, Math.min(remaining, Integer.MAX_VALUE));
69 int read = super.read(b, off, toCopy);
75 * @see java.io.FilterInputStream#skip(long)
78 public synchronized long skip(long n) throws IOException {
79 if ((n < 0) || (remaining == 0)) {
82 long skipped = super.skip(Math.min(n, remaining));
90 * This method does nothing, as {@link #mark(int)} and {@link #reset()} are
93 * @see java.io.FilterInputStream#mark(int)
96 public void mark(int readlimit) {
103 * @see java.io.FilterInputStream#markSupported()
104 * @return <code>false</code>
107 public boolean markSupported() {
114 * This method does nothing, as {@link #mark(int)} and {@link #reset()} are
117 * @see java.io.FilterInputStream#reset()
120 public void reset() throws IOException {
125 * Consumes the input stream, i.e. read all bytes until the limit is
128 * @throws IOException
129 * if an I/O error occurs
131 public void consume() throws IOException {
132 while (remaining > 0) {