创建IO流对象

时间:2011-07-12 20:08:19

标签: java properties io

我运行FindBugs来检查我的代码并且它抱怨该方法可能无法关闭流:

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

是错误还是假阳性?这个流会被正确关闭吗?

2 个答案:

答案 0 :(得分:4)

流处理很繁琐(在Java 7之前)。在此之前,您必须手动关闭流。

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

apache commons-lang可以通过finally缩短IOUtils.closeQuitely(is)子句,但请注意它隐藏了异常

答案 1 :(得分:2)

FindBugs是正确的,流将保持打开状态(至少在程序结束或垃圾收集之前)。传递给load()方法的流不会因API状态而关闭。

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