如何在读取属性文件时关闭fileInputStream

Beg*_*ner 9 java

我有以下代码:

    // Read properties file.
     Properties properties = new Properties();
     try {
     properties.load(new FileInputStream("filename.properties"));
     } catch (FileNotFoundException e) {
     system.out.println("FileNotFound");
     }catch (IOException e) {
     system.out.println("IOEXCeption");
     }
Run Code Online (Sandbox Code Playgroud)

是否需要关闭FileInputStream?如果是的话,我该怎么做?我的代码清单中出现了错误的练习错误.要求它最终阻止.

hmj*_*mjd 12

你必须关闭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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

从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");
}
Run Code Online (Sandbox Code Playgroud)