Reputation: 610
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).
Upvotes: 1
Views: 1416
Reputation: 4211
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);
Upvotes: 0