您必须关闭FileInputStream
,因为Properties
实例不会。从Properties.load()
javadoc:
此方法返回后,指定的流保持打开状态。
将 存储FileInputStream
在一个单独的变量中,在外部声明try
并添加一个finally
块,FileInputStream
如果它被打开则关闭:
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream("filename.properties");
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
} finally {
if (null != fis)
{
try
{
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
从 Java 7 开始使用try-with-resources :
final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
}