How do I avoid closing an InputStream passed to my method that I wrap in Reader streams?

Viewed 7773

I'm creating a Java method that accepts a single InputStream as an argument. For the convenience of working with a character-based stream, I wrap the provided InputStream at the start of the method implementation as follows:

public void doStuff(InputStream inStream) {
   BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
   ...
}

Since the InputStream (inStream) is passed to my method, I don't want to close it ... as I think that should be the responsibility of the client calling my method (is this assumption correct?). However, I do think that I should close the BufferedReader that I created; but in doing so, I believe it will automatically close all the other composed streams including the inStream.

Does anyone see a way for me to close the BufferedReader and InputStreamReader that I created while not closing the InputStream passed to my method? Maybe there is a way to make a copy of the provided InputStream before I wrap it? Thanks

4 Answers

NoCloseInputStream

You might found this class in your classpath. Implementations are known from hibernate and sun. If so, you could use this class as a wrapper. Good luck.

CloseIgnoringInputStream

This one comes with apache-poi.

CloseSuppressingInputStream

This one is from hibernate.

KeepAliveInputStream

This one has a no-op close method too.

StreamUtils.nonClosing() - Spring

From now it should be clear: Not closing a inputstream is a common requirement. This one comes from spring.

Thats all from my usual classpath.

Related