Thinhbk
Thinhbk

Reputation: 2214

InputStream reads data from offset

I'd like to implement a generic, re-usable class that allow to set Offset on the stream before reading data. Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.

I found a solution in SO about PositionInputStream, but it's not exactly what I want. Can anyone recommend an existing implementation of a Offset InputStream?

Upvotes: 0

Views: 2756

Answers (1)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

I think that at the end, all implementations will at best read the first "offset bytes",
but will not present this to the user,
and then return the user what he expects to be the read bytes.

For example , let's say your Infrastructure is based on a decorator pattern and holds a "wrapped" InputStream as a member.

The code of read method (with offset and length parameters) can look more or less like:


public int read(byte[] b,
                int off,
                int len)
         throws IOException {
    innerInputStream.read(b,off,len);
}


InputStreamDecorator d = new InputStreamDecorator(new FileInputStream("myfile.txt"));

You can have also a wrapping implementation of skip.
You can decide to have a CTOR that will have an argument of number of bytes to skip, and this CTOR will call the internal skip method.
For example:

public class InputStreamDecorator extends InputStream {
   public InputStreamDecorator(InputStream is, long toSkip) {
      this.internalStream = is;
      is.skip(toSkip);
   }
}

Upvotes: 1

Related Questions