Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I close a BufferedInputStream, is the underlying InputStream also closed? [duplicate]

InputStream in = SomeClass.getInputStream(...);
BufferedInputStream bis = new BufferedInputStream(in);

try {
    // read data from bis
} finally {
    bis.close();
    in.close();    
}

The javadoc for BufferedInputStream.close() doesn't mention whether or not the underlying stream is closed:

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

Is the explicit call to in.close() necessary, or should it be closed by the call to bis.close()?

like image 916
Graham Borland Avatar asked Jun 23 '14 09:06

Graham Borland


People also ask

What is the difference between InputStream and BufferedInputStream?

DataInputStream is a kind of InputStream to read data directly as primitive data types. BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data. data is basicaly read ahead of time and this reduces disk or network access.

What happens if you don't close an InputStream?

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.

Does InputStream need to be closed?

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.

How does BufferedInputStream work in Java?

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created.


2 Answers

From the source code of BufferedInputStream :

public void close() throws IOException {
    byte[] buffer;
    while ( (buffer = buf) != null) {
        if (bufUpdater.compareAndSet(this, buffer, null)) {
            InputStream input = in;
            in = null;
            if (input != null)
                input.close();
            return;
        }
        // Else retry in case a new buf was CASed in fill()
    }
}

So the answer would be : YES

like image 72
omu_negru Avatar answered Oct 13 '22 03:10

omu_negru


BufferedInputStream doesn't hold any system resources itself; it simply wraps around an InputStream which holds those resources. Therefore the BufferedInputStream forwards the close operation onto the wrapped InputStream which will then release its resources.

like image 31
ConMan Avatar answered Oct 13 '22 01:10

ConMan