Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing I/O resource properly

Tags:

java

file

io

I was wondering that what is the best/appropriate way to release file resources/handles.

Traditional code,

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

}

Will the file handle be released by closing BufferredInputStream.close alone or it needs the underlying stream(i.e. FileInputStream.close()) also to be called explicitly.

P.S. Javadoc for [FilterOutputStream.close] method specifies that it will explicitly close the underlying stream too. But other streams doesn't seem to have this in the doc.

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

Please advice. Thanks in advance.

like image 532
Rajkumar Palani Avatar asked Dec 26 '12 13:12

Rajkumar Palani


2 Answers

You can always check the source code for the underlying class to determine the exact behavior.

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

The source code is available here

like image 96
Rahul Avatar answered Nov 08 '22 16:11

Rahul


Your approach is correct. When in doubt, always check the source code. http://www.docjar.com/html/api/java/io/BufferedInputStream.java.html the close method is closing "in" which was chained to BufferedInputStream.

like image 32
Usman Saleem Avatar answered Nov 08 '22 15:11

Usman Saleem