问题描述
我已经找到了几个类似的问题,但仍然找不到我的问题的答案.
I've found several similar questions, but I still can't find the answer to my question.
我知道关闭外部流就足够了,它将关闭按行创建的内部流.
I know that it is enough to close the outer stream and it will close inner stream which is created in line.
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()之后立即自动将其关闭./code>方法调用,因为没有对资源的引用?
Should the FileInputStream
be assigned to a variable and then closed explicitly (or with try-with-resource construction) or will Java GC close it automatically right after props.load()
method invocation, because there is no reference to the resource?
推荐答案
Javadoc指出
是的,如果您想编写简洁的代码,则应自行关闭它.GC最终将关闭它,如果它会绕过流上的调用 finalize()
方法(如下所示),但是您.
So yes, you should close it yourself if you want to write clean code. The GC will close it eventually, if it gets around to calling the finalize()
method (shown below) on the stream, but you shouldn't rely on that.
始终关闭您的资源,这是唯一可以确保的方法.
Always close your resources, that's the only way to be sure.
/**
* 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();
}
}
这篇关于内联创建的InputStream是否由GC自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!