Java – how do I avoid closing the InputStream passed to my method wrapped in the reader stream?

I'm creating a Java method that accepts a single InputStream as a parameter To facilitate the use of character based streams, I will start with the implementation of the provided InputStream wrapper method as follows:

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

Because of the method passed to me by InputStream (instream), I don't want to close it... Because I think it should be the responsibility of the client to call my method (is this correct? However, I think I should close the BufferedReader I created; but when doing so, I believe it will automatically close all other composite streams, including instream

Has anyone seen a way to close the BufferedReader and inputstreamreader I'm creating without closing the InputStream passed to my method? May there be a way to wrap a copy of the provided InputStream? thank you

Solution

When you do not want to close the underlying reader, you do not need to close BufferedReader or inputstreamreader or most reader implementations

These readers do not have any resources, the call to close () will be free, and the garbage collector will not be free (such as the value in native resources or static variables) when you put the reference in the reader's last method

The underlying input stream that communicates with native resources, such as FileInputStream or stream obtained from URL, must be closed to release these native resources

For writers, close () usually calls flush () with one difference However, you can call flush () directly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>