Closing Streams in Java

后端 未结 6 2330
再見小時候
再見小時候 2020-11-27 18:27

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

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 18:44

    File handles are scarce, finite resources. You can run out of them if you don't clean them up properly, just like database connections.

    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.

提交回复
热议问题