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
resource-leak is probably more of a concern here. Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.
You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.
InputStream is just an "interface" in terms of close() . InputStreamReader will not close an interface. It will close the underlying data resource (like file descriptor) if it is. It will do nothing if close is override and empty in an implementation.
You don't have to close ByteArrayInputStream , the moment it is not referenced by any variable, garbage collector will release the stream and somebytes (of course assuming they aren't referenced somewhere else).
You do not need to close a BufferedReader
or InputStreamReader
or probably most reader implementations, when you do not wish to close the underlying reader.
These readers do not hold any resources that a call to close()
would make free and which the garbage collector would not make free anyway (e.g. native resources or values in static variables) when you drop the reference to the reader at the end of your method.
The underlying input streams that communicate with native resources, e.g. FileInputStream
or streams obtained from URLs, must be closed to free those native resources.
For Writer
, there's a difference in that close()
usually calls flush()
. But then, you can call flush()
directly.
Personally I would just avoid the problem by changing the signature of your method to require that a BufferedReader (or Reader) be passed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With