gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:16 25 4
gpt4 key购买 nike

我有以下代码:

    // 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");
}

是否需要关闭FileInputStream?如果是,我该怎么做?我的代码 list 中出现错误做法错误。要求它放入 finally block 。

最佳答案

您必须关闭 FileInputStream,因为 Properties 实例不会。来自 Properties.load() javadoc:

The specified stream remains open after this method returns.

FileInputStream 存储在一个单独的变量中,在 try 之外声明,并添加一个 finally block 来关闭 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();
}
}
}

使用try-with-resources从 Java 7 开始:

final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOEXCeption: " + e.getMessage());
}

关于java - 如何在读取属性文件时关闭 fileInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11430289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com