关闭Java InputStreams [英] Closing Java InputStreams

查看:134
本文介绍了关闭Java InputStreams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Java InputStreams时,我对close()方法的用法有一些疑问。从我看到和从大多数开发人员那里读到的内容,你应该总是在不再需要的时候在InputStream上显式调用close()。但是,今天我正在研究使用Java属性文件,我发现的每个例子都是这样的:

I have some questions about the usage of the close() method when using Java InputStreams. From what I see and read from most developers, you should always explicitly call close() on an InputStream when it is no longer needed. But, today I was looking into using a Java properties file, and every example I have found has something like this:

Properties props = new Properties();
try {
    props.load(new FileInputStream("message.properties"));
    //omitted.
} catch (Exception ex) {}

通过上面的例子,没有办法显式调用close()因为InputStream在使用后无法访问。我已经看到了许多类似的InputStreams用法,尽管它似乎与大多数人对明确关闭的说法相矛盾。我阅读了Oracle的JavaDocs,但没有提到Properties.load()方法是否关闭了InputStream。我想知道这是否普遍可以接受,或者是否更喜欢做以下事情:

With the above example, there is no way to explicitly call close() because the InputStream is unreachable after it is used. I have seen many similar uses of InputStreams even though it seems to contradict what most people say about explicitly closing. I read through Oracle's JavaDocs and it does not mention if the Properties.load() method closes the InputStream. I am wondering if this is generally acceptable or if it is preferred to do something more like the following:

Properties props = new Properties();
InputStream fis = new FileInputStream("message.properties");
try {
    props.load(fis);
    //omitted.
} catch (Exception ex) {
    //omitted.
} finally {
    try {
        fis.close();
    } catch (IOException ioex) {
        //omitted.
    }
}

哪种方式更好和/或效率更高?或者它真的重要吗?

Which way is better and/or more efficient? Or does it really matter?

推荐答案

属性教程加载后显式关闭 FileInputStream ,所以我认为它是安全的假设 load 方法不对它负责,你是。

The examples in the Properties Tutorial close the FileInputStream explicitly after loading, so I think it's safe to assume that the load method isn't responsible for it, you are.

// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();

仅供参考,我检查了 Apache Harmony 实现属性,它在加载时关闭流。

Just for reference, I checked the Apache Harmony implementation of Properties, and it does not close the stream on load.

这篇关于关闭Java InputStreams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆