How do I avoid closing an InputStream passed to my method that I wrap in Reader streams?
I'm creating a Java method that accepts a single InputStream
as an argument. For the convenience of working with a characte开发者_如何学Pythonr-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
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.
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.
Personally I would just avoid the problem by changing the signature of your method to require that a BufferedReader (or Reader) be passed in.
What I'd try would be overriding the close
method:
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)){
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
}
}
};
// rest of your code
Kind of crazy, but it should work. Though, I'm not sure this is the best approach.
I think this is an interesting question, so I hope someone expert gives his/her opinion.
精彩评论