java - 内联创建的 InputStream 是否被 GC 自动关闭?

标签 java garbage-collection inputstream

我已经找到了几个类似的问题,但我仍然找不到我的问题的答案。

我知道关闭外部流就足够了,它将关闭在线创建的内部流。

BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
br.close();

考虑下一个例子

Properties props = new Properties();
props.load(new FileInputStream(configPath));

是否应该将 FileInputStream 分配给变量然后显式关闭(或使用 try-with-resource 构造),或者 Java GC 会在 props.load()< 之后立即自动关闭它 方法调用,因为没有对资源的引用?

最佳答案

Javadoc 指出

The specified stream remains open after this method returns.

所以是的,如果您想编写干净的代码,您应该自己关闭它。 GC 最终将关闭它,if 它开始调用流上的 finalize() 方法(如下所示),但是您 shouldn't rely on that .

始终关闭您的资源,这是唯一可以确定的方法。

/**
 * Ensures that the <code>close</code> method of this file input stream is
 * called when there are no more references to it.
 *
 * @exception  IOException  if an I/O error occurs.
 * @see        java.io.FileInputStream#close()
 */
protected void finalize() throws IOException {
    if ((fd != null) &&  (fd != FileDescriptor.in)) {
        /* if fd is shared, the references in FileDescriptor
         * will ensure that finalizer is only called when
         * safe to do so. All references using the fd have
         * become unreachable. We can call close()
         */
        close();
    }
}

关于java - 内联创建的 InputStream 是否被 GC 自动关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45456509/

相关文章:

java - 合并两个数组而不使用额外空间

java - android.view.InflateException : Binary XML <Unknown>, 和 OutOfMemoryError?

python-3.x - 创建实例失败时调用的析构函数?

android - 将激光测距仪 (Bosch Disto GLM 50 C) 与智能手机 (Android Studio) 连接

java - 错误找不到符号变量UTF_8 android studio

java - 在 java 中调用 System.gc() 是否建议对老一代和年轻一代进行垃圾收集?

java - JPA 的软引用

java - BufferedInputStream.available() 在套接字编程中可靠吗?

java - 为什么我的数组元素不能被正确解析?

java - 字符串未在条件中声明?