Closing Streams in Java

Solution 1:

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.

Solution 2:

Yes, when the process terminates the unmanaged resources will be released. For InputStreams this is fine. For OutputStreams, you could lose an buffered data, so you should at least flush the stream before exiting the program.

Solution 3:

Dude. If you don't close your stream, your unit test will fail. Or at least, it should. So, that's why you need to close it. ;)

And while the OS will almost certainly clean up if you just exit, they'll generally get freed up faster if you explicitly close them. Furthermore, what if your code ends up in a long-running program sometime down the road? Then they'll have problems and curse you. :(

So, it's like washing your hands after using the bathroom. Eventually someone will pay the price if you don't do it. You can get away with it for a while, but it's still a good practice.