I have an InputStream which contains XML data which I would like to parse before returning the InputStream.
InputStream is = myObj.getInputStream(); // parse Inputstream here return is;
Of course I could save the stream as a byte array and return a new InputStream from that or
create a second InputStream on 'myObj'.
But is there any way to parse the stream 'on the fly'?
Edit:
Basically I am searching for a way to re-use the stream after parsing. Sort of parsing the stream without consuming it, respectively to reset it after the parsing.
Solution:
The solution I've found is to use a BufferedInputStream (Note from the comments: That will only work up to 8k bytes)
BufferedInputStream is = new BufferedInputStream ( myObj.getInputStream() ); is.mark( Integer.MIN_VALUE ); // parse Inputstream here is.reset(); return is;
This can be quite complicated because the best candidate for on-the-fly xml parsing the SAX Parser. By necessity it is event driven and relies on callback methods to indicate events in the incoming stream.
I have implemented something like this by doing the following:
This is not simple but it is stable and reliable. I will try to post some demo code.