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

JoJ*_*oJo 6 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案只是像Eclipse建议的那样,并在finally块中执行此操作吗?

finally {
    try {
        fileInputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢大家!

Jef*_*rey 16

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

try (FileInputStream fileIn = ...) {
    // do something
} // fileIn is closed
catch (IOException e) {
    //handle exception
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*Lin 8

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


Boh*_*ian 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
    }
}
Run Code Online (Sandbox Code Playgroud)