我需要使用try / catch / finally块来包围fileInputStream.close吗?怎么做?

时间:2012-07-24 00:10:36

标签: java oop try-catch-finally

我有以下Java类做一件事,从config.properties中激活值。

当关闭fileInputStream时,我想我在维基百科上读到,最好将它放在最后一个块中。因为它在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();
    }
}

谢谢大家!

3 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分:7)

因为FileInputStream.close()抛出IOException,而finally {}块没有捕获异常。所以你需要捕获它或声明它才能编译。 Eclipse的建议很好;捕获finally {}块中的IOException。

答案 2 :(得分:7)

标准方法是:

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
    }
}