0

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?

Community
  • 1
  • 1
Thinhbk
  • 2,194
  • 1
  • 23
  • 34

1 Answers1

1

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);
   }
}
Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27
  • 1
    You don't need reflection, `skip(long)` is declared by the base `InputStream` class (and implemented by reading and discarding, but subclasses may be more efficient). – Ian Roberts Oct 31 '12 at 11:51
  • 1
    I figured out that using skip() method is correct way, thank. – Thinhbk Oct 31 '12 at 16:19