Java 我是否需要用try/catch/finally块包围fileInputStream.close?怎么做的?

Java 我是否需要用try/catch/finally块包围fileInputStream.close?怎么做的?,java,oop,try-catch-finally,Java,Oop,Try Catch Finally,我有一个Java类,它做一件事,从config.properties中激发值 当需要关闭文件输入流时,我想我在维基百科上读到,把它放在finally块中是件好事。因为它确实在try/catch块中工作得很好 您能给我演示一下在最后一节中获取fileInputStream.close()的更正吗 ConfigProperties.java 包装基地 import java.io.FileInputStream; import java.util.Properties; public class

我有一个Java类,它做一件事,从
config.properties
中激发值

当需要关闭
文件输入流时,我想我在维基百科上读到,把它放在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();
    }
}

因为
FileInputStream.close()
抛出IOException,而finally{}块不会捕获异常。因此,为了编译,您需要捕获或声明它。Eclipse的建议很好;捕获finally{}块中的IOException。

是的,这是常见的Java 7之前的解决方案。但是,随着Java 7的引入,现在有一些语句将在
try
块退出时自动关闭所有声明的资源:

try (FileInputStream fileIn = ...) {
    // do something
} // fileIn is closed
catch (IOException e) {
    //handle exception
}

标准方法是:

FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream(...);
    // do something with the inputstream
} catch (IOException e) {
    // handle an exception
} finally { //  finally blocks are guaranteed to be executed
    // close() can throw an IOException too, so we got to wrap that too
    try {
        if (fileInputStream != null) {
            fileInputStream.close();
        }        
    } catch (IOException e) {
        // handle an exception, or often we just ignore it
    }
}

仅供参考:commons io有一个很好的函数:IOUtils.closequityle(),它将处理关闭时的try/catch。您的代码看起来会更好:)请记住,此函数不会给您响应IOException的机会,但通常人们不会这样做,并且会忽略异常。如果您需要响应,请创建自己的实用程序方法,记录或打印堆栈跟踪或任何您需要执行的操作。您也可以使用Commons IO中的方法。它包装close方法以删除抛出的所有IOException。比使用另一个try/catch块更干净。