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;
To parse on the fly, without waiting the end of stream you can use a Sax Parser.
A sax parser is event based so it is not necessary to read the whole document before processing it. With that the process is something like:
For each event you need to execute some custom code.
Working with a sax parser is a little more difficult than a dom parser but has some advantages. Over all it needs less resources and you don't need to wait to have the whole document.