Creating IO stream object
I ran FindBugs to check my code and it complains that method may fail to clos开发者_运维技巧e 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?
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
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
精彩评论