Reputation: 1202
What I am trying to achieve here is have more debug output by printing out the contents of an InputStream using apache-commons. It seems like I am changing the stream itself in the process.
InputStream is = getClass().getResourceAsStream("file.txt");
IOUtils.copy(is, System.out); //Happily Prints out contents of file.txt
IOUtils.copy(is, System.out); //Doesn't print anything
Why does copying a stream using IOUtils change the stream? I tried cloning the stream, and then printing it out but still no luck. I tried CloseShieldInputStream from apache commons to clone.
InputStream is = getClass().getResourceAsStream("file.txt");
CloseShieldInputStream csis = new CloseShieldInputStream(is);
IOUtils.copy(csis, System.out);//Happily Prints out contents of file.txt
IOUtils.copy(is, System.out);//Still Doesn't print anything
Can someone explain why they call these methods 'copy' even though the source stream loses its contents? How can I print out a stream without worrying about losing its contents?
EDIT:
This code (except where the stream gets initialized) is pretty deep inside a 3rd-Party library and the stream is passed after going through several methods. It's hard to figure out where the stream got initialized, and display it there and then reinitialize. I am desperately trying to display this stream and still keep it unaltered.
Upvotes: 0
Views: 2607
Reputation: 17007
The System.out
stream is not being changed. What is happening is that once the contents of is
are read, they have been consumed and you can't read them again. What you have to do to fix this is re-initialize is
before the second call.
Upvotes: 2