Freeing up an I / O resource properly

I was wondering what is the best / suitable way to release file resources / descriptors.

Traditional code

BufferredInputStream stream = null try{ ---- stream = new BufferredInputStream(new FileInputStream()); ---- } finally{ if(stream != null){ stream.close() } 

}

Whether the file descriptor will be released by closing BufferredInputStream.close its own or whether it needs the underlying stream(ie FileInputStream.close()) explicitly.

PS Javadoc for [FilterOutputStream.close] indicates that it also explicitly closes the underlying stream. But other threads don't seem to have this in the document.

 [FilterOutputStream.close]: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FilterOutputStream.html#close%28%29 

I ask for advice. Thanks in advance.

+6
source share
4 answers

You can always check the source code of the base class to determine the exact behavior.

However, in this case, calling close() on the BufferedInputStream will also close the underlying stream, i.e. FileInputStream .

Source code is available here.

+4
source

When multiple threads are chained together, the last one to be created last will close the underlying thread. Thus, closing a BufferedInputStream will also close the underlying FileInputStream .

So you just call close () on one thread and automatically close the underlying thread.

+2
source

Your approach is right. When in doubt, always check the source code. The http://www.docjar.com/html/api/java/io/BufferedInputStream.java.html close method closes the "in" that was bound to the BufferedInputStream.

+2
source

BufferredInputStream itself does not contain system resources, so BufferredInputStream.close () will just propagate the close call to InputStream, which it wraps .. so it should only do well.

0
source

All Articles