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 can I wrap the InputStream in so I may access it multiple times?
Asked
Active
Viewed 4,190 times
0
-
I found this on SO: [this answer] (http://stackoverflow.com/questions/1045632/bufferedreader-for-large-bytebuffer) – bmw0128 Feb 24 '11 at 18:00
3 Answers
1
You can try
byte[] bytes = IOUtils.toByteArray(inputStream);
// as often as desired.
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
1
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.

Jason LeBrun
- 13,037
- 3
- 46
- 42
-
I want to use JAXB, and I'm having an issue with reading the XML multiple times – bmw0128 Feb 24 '11 at 17:21
-
1
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.

M. Jessup
- 8,153
- 1
- 29
- 29