问题描述
在我们离开程序之前,为什么我们需要关闭一个FileInputStream(以及一般的流) ?否则会发生什么?如果程序在程序中明确关闭输入流之前停止,则流是否也会自动关闭?
Why do we need to close a FileInputStream (and streams in general) in any case before we leave the program? What would happen otherwise? If the program stops before the input stream is closed explicitly in the program, doesn't the stream also close automatically?
推荐答案
文件处理是稀缺的,有限的资源。如果你没有正确清理它们就可以用完它们,就像数据库连接一样。
File handles are scarce, finite resources. You can run out of them if you don't clean them up properly, just like database connections.
如果你只用一个用户编写了一个小程序就可以了逃避邋and而不是在finally块中关闭。
If you've written a small program with just one user you can get away with being sloppy and not closing in a finally block.
但是如果你最终在具有许多用户和文件句柄的应用程序中使用该习惯用法,那么你可能会有一个问题。
But if you end up using that idiom in an application that has many users and file handles you might have a problem.
首先我们养成习惯,然后他们就会成就我们。即使没有必要,我也尝试应用最佳实践。
"First we make our habits, then they make us." I try to apply best practices even when they aren't necessary.
这篇关于在Java中关闭Streams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!