8

我有以下 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();
    }
}
4

3 回答 3

22

是的,这是 Java 7 之前的常见解决方案。但是,随着 Java 7 的引入,现在有了try-with-resourcetry语句,当块退出时,它们会自动关闭所有声明的资源:

try (FileInputStream fileIn = ...) {
    // do something
} // fileIn is closed
catch (IOException e) {
    //handle exception
}
于 2012-07-24T00:13:35.407 回答
10

因为FileInputStream.close()抛出一个 IOException,并且 finally{} 块没有捕获异常。因此,您需要捕获它或声明它才能编译。Eclipse 的建议很好;在 finally{} 块中捕获 IOException。

于 2012-07-24T00:12:42.623 回答
10

标准方法是:

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
    }
}
于 2012-07-24T00:18:37.320 回答