I need to repeatedly read from an InputStream. The stream is from reading some XML from a web service request. I'd like to keep the XML in memory so I may parse the stream multiple times, and ultimately trash the XML at some later time. What 开发者_如何学Ccan I wrap the InputStream in so I may access it multiple times?
Assuming you're reading in a well-structured XML document, why not parse the document a single time using a DOM parser (for example, javax.xml.parsers.DocumentBuilder
)?
This will provide you with an in-memory representation of the XML document in a structured format. If you use a parser like DocumentBuilder
, you can subsequently fetch various parts of the structured data using the methods Node
like getElementsByTagName
, etc.
You can try
byte[] bytes = IOUtils.toByteArray(inputStream);
// as often as desired.
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
Apache Commons IO has a utility method that will read an input stream into a byte array (if you didn't want to write the function yourself) you could then wrap that in a ByteArrayInputStream i.e.
InputStream xmlInput = ...;
InputStream rereadableStream =
new ByteArrayInputStream(IOUtils.toByteArray(xmlInput));
and then use mark() / reset() or simply save the byte array and construct a new ByteArrayInputStream when needed.
精彩评论