Meaningless Drivel is fun!
The moose likes I/O and Streams and the fly likes Reuse of InputStreamReader Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Reuse of InputStreamReader" Watch "Reuse of InputStreamReader" New topic

Reuse of InputStreamReader

Erik Pragt
Ranch Hand

Joined: Sep 08, 2001
Posts: 125
Hello everyone,
I have a very small problem, but I just can't figure out how to solve it.
I have created an InputStreamReader from a URLConnection, which I use to process some XML data (in other words: the InputStream is an XML response).
Now I want to do 2 things with the inputstream:
1) print it to screen
2) process it (as said before)
But the problem is: after I processed it, the internal pointer of the InputStreamReader is pointing to the end of the stream, causing the XML processing to fail.
Maybe I could first clone the inputstream, but as I have no previous experience with clone, I'd like to delay using it untill I know enough about it.
So if anyone could help me, please let me know. It's giving me a headache!!
Have a nice Christmas,
Erik Pragt
Nayanjyoti Talukdar
Ranch Hand

Joined: Feb 12, 2002
Posts: 71
During the process time, u can either write the data to a file or put these into a StringBuffer object and each time append the data.
That way, as soon as the process gets over, u'r data will be stored in a file or some other object. If the process takes place first, then the InputStream pointer will reach end of the data, and then it won't display anything.
I think this will help....Merry Christmas!!
Erik Pragt
Ranch Hand

Joined: Sep 08, 2001
Posts: 125
Thanks for your answer!
However, I really need to reuse the inputstream, because I use it for parsing XML, and the XML parser can only take an inputstream as input.
Maybe you (or someone else) has an other suggestion?
Greetings, Erik
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Printing to screen is easily done by a custom FilterReader.

Then just write something like
XMLParser.parse(new EchoReader(reader));
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
You could also copy all the input to a CharArrayWriter to obtain the file as a char[] and create two seperate CharArrayReaders for reading purposes. That would require holding the entire file contents in memory, though.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
hey David,
i was able to understand the problem reading your answer
i liked the FilterReader thing. its cool. i have never used it but its a good idea for filtering...
thanks, it was helpful.
I agree. Here's the link:
subject: Reuse of InputStreamReader
It's not a secret anymore!