Dima
Dima

Reputation: 1828

Creating IO stream object

I ran FindBugs to check my code and it complains that method may fail to close stream:

Properties prop = new Properties();
prop.load(new FileInputStream("file.txt"));
...

Is it a mistake or just false positive? Will this stream be properly closed?

Upvotes: 1

Views: 183

Answers (2)

Bozho
Bozho

Reputation: 597274

Stream handling is tedious (prior to Java 7). Before that you have to manually close the stream.

InputStream is = null;
try {
   is = new FileInputStream(..);
   // do something with stream
} finally {
   try {
      is.close();
   } catch (Exception ex){ 
      //report problem
   }
}

apache commons-lang can shorten the finally clause by its IOUtils.closeQuitely(is), but note that it hides the exception

Upvotes: 4

dontocsata
dontocsata

Reputation: 3071

FindBugs is correct, the stream will remain open (at least until the end of the program or it is garbage collected). The stream tyou pass to the the load() method is not closed as the API states.

See: http://download.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.InputStream%29

Upvotes: 2

Related Questions