我有以下 Java 类,它做一件事,从config.properties
.
当需要关闭 时fileInputStream
,我想我在 Wikipedia 上读到,将它放在 finally 块中是件好事。因为它在 try/catch 块中确实可以正常工作。
你能告诉我更正以进入fileInputStream.close()
最后的部分吗?
ConfigProperties.java 包库;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigProperties {
public FileInputStream fileInputStream;
public String property;
public String getConfigProperties(String strProperty) {
Properties configProperties = new Properties();
try {
fileInputStream = new FileInputStream("resources/config.properties");
configProperties.load(fileInputStream);
property = configProperties.getProperty(strProperty);
System.out.println("getConfigProperties(" + strProperty + ")");
// use a finally block to close your Stream.
// If an exception occurs, do you want the application to shut down?
} catch (Exception ex) {
// TODO
System.out.println("Exception: " + ex);
}
finally {
fileInputStream.close();
}
return property;
}
}
解决方案是否只能按照 Eclipse 的建议执行并在 finally 块中执行?
finally {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}