1

I have a ServletInputStream that can be very big and I want to extract the first X bytes of the InputStream and then let the stream in it initial state.

What I have done for now is markSupported(), mark() and reset() but the markSupported return false so I need to implement an other way of doing it.

A solution is described here to read an input stream twice, but the problem is that my stream can be very big in size and I can't have all of it in memory (moreover i am not sure that the max array size will be enough).

Is there a way to just read a small number of bytes and then put the stream in it initial state. The workaround will be to consume the X bytes I want to read an then let the stream consumed pass X bytes in addition to the following process (which I want to avoid).

bloub
  • 510
  • 1
  • 4
  • 21

2 Answers2

2

BufferedInputStream.markSupported() returns true (see Javadoc). Simply wrap your stream with BufferedInputStream and set a mark limit bigger than X.

Pino
  • 7,468
  • 6
  • 50
  • 69
0

Have you looked at java.io.PushbackInputStream?

If I am understanding you correctly, it seems like a good fit for what you want to achieve, especially if the bytes you want to examine are at the beginning of the stream.

byte[] peekBuffer = new byte[n];
PushbackInputStream pis = new PushbackInputStream(yourStream, peekBuffer.length);

pis.read(peekBuffer);
// Examine peekBuffer

// Reinsert the peeked bytes.
pis.unread(peekBuffer);
Daniel
  • 4,033
  • 4
  • 24
  • 33