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



我有下面的Java类,它做一件事,从config.properties中激发值。

到了关闭fileInputStream的时候,我想我在维基百科上读到,把它放在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();
    }
}

是的,这是Java 7之前的常见解决方案。然而,随着Java 7的引入,现在有了try-withresource语句,当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
    }
}

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

关闭流是一个好习惯,因为它在后台所做的叫做缓冲,这意味着它不会释放内部缓冲区,也不会释放文件描述符

相关内容

  • 没有找到相关文章

最新更新