在 Java 中关闭流 [英] Closing Streams in Java

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

问题描述

为什么我们需要在离开程序之前关闭 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.

如果你编写了一个只有一个用户的小程序,你可以避免草率而不是在 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 中关闭流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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