Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do closing InputStreamReader also close underlying InputStream?

Tags:

java

JavaDoc for InputStreamReader doesn't say anything about closing the underlying InputStream:

https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html#close--

Description copied from class: Reader

Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

Does closing an InputStreamReader also close the underlying InputStream?

UPDATE In:

InputStreamReader istream = new InputStreamReader(conn.getInputStream(), "UTF-8")
istream.close();

Do I need to close conn.getInputStream()?

InputStreamReader implementation direct close call to StreamDecoder which is a native class.

like image 584
gavenkoa Avatar asked Jun 21 '17 10:06

gavenkoa


1 Answers

As other answers and comments said, the answer is yes, it does close the InputStream. You can see for yourself with the following code:

    InputStream is = new FileInputStream("D:\\a.txt");
    Reader r = new InputStreamReader(is);
    r.close();
    is.read();  // throws exception: stream is closed.

Therefore, if you close the Reader, you don't need to also close the InputStream. However, I guess you are using try-with-resources everywhere (aren't you? ;) ) and the InputStream as well as the Reader will both be closed at the end of the try block. That doesn't matter, because an InputStream can be closed multiple times; it's a no-op if the stream is already closed.

If you want to avoid closing the InputStream, you can write a simple wrapper that does nothing when it is closed:

    class UncloseableInputStream extends FilterInputStream {
        public UncloseableInputStream(InputStream is) {
            super(is);
        }
        public void close() {
            // Do nothing.
        }
    }

    InputStream is = new FileInputStream("D:\\a.txt");
    Reader r = new InputStreamReader(new UncloseableInputStream(is));
    r.close();
    is.read();  // still works despite closing the reader.
like image 55
Klitos Kyriacou Avatar answered Oct 17 '22 05:10

Klitos Kyriacou