0

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?

bmw0128
  • 13,470
  • 24
  • 68
  • 116
  • I found this on SO: [this answer] (http://stackoverflow.com/questions/1045632/bufferedreader-for-large-bytebuffer) – bmw0128 Feb 24 '11 at 18:00

3 Answers3

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
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