Currently, I have a method :
void method(InputStream stream) {
// Create UTF-8 reader by wrapping up the stream.
}
The reason I do not want to have method to accept Reader is that, I want my own method to have own control to decide what type of encoding should be used.
The problem is, whenever I close the Reader, InputStream will be closed as well. This is not my intention. As InputStream is “opened” by the caller. Hence, the closing operation on InputStream shall be done at caller side.
Is there any way I can close the Reader in “method”, without closing the InputStream passed by caller?
Thanks.
If you don’t want to close the input stream, just don’t close the reader. Closing the reader will serve no purpose other than to close the input stream, after all.
That’s assuming your method would be closing the reader… if it wouldn’t be, then overriding
close()in your ownReaderimplementation (e.g. deriving fromInputStreamReader) or overridingclose()in aFilterInputStreamas per the other answers should be fine.EDIT: The comments have expressed some concerns about resource leakage. It’s true that in theory,
InputStreamReader(which is the kind of reader you’re most likely to be using) could be doing something else behind the scenes… writing the output to a file as it goes, for example. In reality, that’s simply not going to happen.close()is just going to close the stream (via aStreamDecoder, in fact – at least in the JDK 6 implementation). The only unmanaged resource involved is the stream itself… and you want to effectively leak that.For an input stream, there’s no such concept as “flush” – what would it even do? There’s basically nothing to clean up apart from the input stream and structures in memory… the GC will take care of the memory, so you’re done.
Using a
FilterInputStreamis a generally cleaner approach, I’ll certainly concede that – but for this specific case I’d just not close the reader. Heck, that’ll make the code simpler than normal, as you’d usually want a try/finally block to make sure you closed it in all situations. All of that can just go.Note that if you were publishing the reader to any other code, all of the above logic would be null and void – you’d want to close the reader to stop the other code from potentially using it when they shouldn’t. In this case though, I’m anticipating that you’ll construct the reader, read from it, and then just let it get garbage collected, never publishing the reference elsewhere.