我已经找到了几个类似的问题,但我仍然找不到我的问题的答案。
我知道关闭外部流就足够了,它将关闭在线创建的内部流。
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/