| /** |
| * |
| */ |
| package org.eclipse.epp.installer.internal.archive.sfx; |
| |
| import java.io.IOException; |
| import java.io.InputStream; |
| import java.io.RandomAccessFile; |
| |
| |
| /** |
| * @author itsuart |
| * |
| */ |
| public class BoundedInputStream extends InputStream { |
| |
| private RandomAccessFile file; |
| private long dataLeft; |
| /** |
| * |
| */ |
| public BoundedInputStream(RandomAccessFile source, long maxSize) { |
| file = source; |
| dataLeft = maxSize; |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#read() |
| */ |
| public int read() throws IOException { |
| if (dataLeft == 0) |
| return -1; |
| int result = file.read(); |
| if ( result != - 1) |
| dataLeft--; |
| return result; |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#available() |
| */ |
| public int available() throws IOException { |
| return (int) dataLeft; |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#markSupported() |
| */ |
| public boolean markSupported() { |
| return false; |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#read(byte[], int, int) |
| */ |
| public int read(byte[] b, int off, int len) throws IOException { |
| if (dataLeft == 0) |
| return -1; |
| if (dataLeft >= len) |
| { |
| int dataRead = file.read(b, off, len); |
| if ( dataRead == -1 ) |
| { |
| dataLeft = 0; |
| return -1; |
| } |
| dataLeft -= dataRead; |
| return dataRead; |
| } |
| else |
| { |
| //read only allowed num of bytes |
| int dataRead = file.read(b, off, (int) dataLeft); |
| if ( dataRead == -1 ) |
| { |
| return -1; |
| } |
| dataLeft -= dataRead; |
| return dataRead; |
| } |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#read(byte[]) |
| */ |
| public int read(byte[] b) throws IOException { |
| return read(b,0,b.length); |
| } |
| /* (non-Javadoc) |
| * @see java.io.InputStream#skip(long) |
| */ |
| public long skip(long n) throws IOException { |
| if (dataLeft == 0) |
| return -1; |
| long bytesToSkip = dataLeft >= n ? n : dataLeft; |
| int skipped = file.skipBytes((int) bytesToSkip); |
| if (skipped == -1) |
| return -1; |
| else |
| { |
| dataLeft -= skipped; |
| return skipped; |
| } |
| } |
| |
| |
| |
| } |