Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create constrained InputStream to read only part of the file?

I want to create an InputStream that is limited to a certain range of bytes in file, e.g. to bytes from position 0 to 100. So that the client code should see EOF once 100th byte is reached.

like image 540
alex2k8 Avatar asked May 22 '10 13:05

alex2k8


3 Answers

The read() method of InputStream reads a single byte at a time. You could write a subclass of InputStream that maintains an internal counter; each time read() is called, update the counter. If you have hit your maximum, do not allow any further reads (return -1 or something like that).

You will also need to ensure that the other methods for reading read_int, etc are unsupported (ex: Override them and just throw UnsupportedOperationException());

I don't know what your use case is, but as a bonus you may want to implement buffering as well.

like image 147
danben Avatar answered Nov 10 '22 00:11

danben


As danben says, just decorate your stream and enforce the constraint:

public class ConstrainedInputStream extends InputStream {
  private final InputStream decorated;
  private long length;

  public ConstrainedInputStream(InputStream decorated, long length) {
    this.decorated = decorated;
    this.length = length;
  }

  @Override public int read() throws IOException {
    return (length-- <= 0) ? -1 : decorated.read();
  }

  // TODO: override other methods if you feel it's necessary
  // optionally, extend FilterInputStream instead
}
like image 8
McDowell Avatar answered Nov 10 '22 00:11

McDowell


Consider using http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/LimitInputStream.html

like image 4
whiskeysierra Avatar answered Nov 10 '22 01:11

whiskeysierra