Stuart McCulloch | 26e7a5a | 2011-10-17 10:31:43 +0000 | [diff] [blame^] | 1 | package aQute.lib.io; |
| 2 | |
| 3 | import java.io.*; |
| 4 | |
| 5 | public class LimitedInputStream extends InputStream { |
| 6 | |
| 7 | final InputStream in; |
| 8 | final int size; |
| 9 | int left; |
| 10 | |
| 11 | public LimitedInputStream(InputStream in, int size) { |
| 12 | this.in = in; |
| 13 | this.left = size; |
| 14 | this.size = size; |
| 15 | } |
| 16 | |
| 17 | @Override public int read() throws IOException { |
| 18 | if (left <= 0) { |
| 19 | eof(); |
| 20 | return -1; |
| 21 | } |
| 22 | |
| 23 | left--; |
| 24 | return in.read(); |
| 25 | } |
| 26 | |
| 27 | @Override public int available() throws IOException { |
| 28 | return Math.min(left, in.available()); |
| 29 | } |
| 30 | |
| 31 | @Override public void close() throws IOException { |
| 32 | eof(); |
| 33 | in.close(); |
| 34 | } |
| 35 | |
| 36 | protected void eof() { |
| 37 | } |
| 38 | |
| 39 | @Override public synchronized void mark(int readlimit) { |
| 40 | throw new UnsupportedOperationException(); |
| 41 | } |
| 42 | |
| 43 | @Override public boolean markSupported() { |
| 44 | return false; |
| 45 | } |
| 46 | |
| 47 | @Override public int read(byte[] b, int off, int len) throws IOException { |
| 48 | int min = Math.min(len, left); |
| 49 | if (min == 0) |
| 50 | return 0; |
| 51 | |
| 52 | int read = in.read(b, off, min); |
| 53 | if (read > 0) |
| 54 | left -= read; |
| 55 | return read; |
| 56 | } |
| 57 | |
| 58 | @Override public int read(byte[] b) throws IOException { |
| 59 | return read(b,0,b.length); |
| 60 | } |
| 61 | |
| 62 | @Override public synchronized void reset() throws IOException { |
| 63 | throw new UnsupportedOperationException(); |
| 64 | } |
| 65 | |
| 66 | @Override public long skip(long n) throws IOException { |
| 67 | long count = 0; |
| 68 | byte buffer[] = new byte[1024]; |
| 69 | while ( n > 0 && read() >= 0) { |
| 70 | int size = read(buffer); |
| 71 | if ( size <= 0) |
| 72 | return count; |
| 73 | count+=size; |
| 74 | n-=size; |
| 75 | } |
| 76 | return count; |
| 77 | } |
| 78 | } |