Alex Rivera | Logout

Closing Streams in Java

Asked 2009-02-05T13:55:45.320
52

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?

Edit
Report

2 Answers

8

Sort of. The stream is backed by a "real" operating system file descriptor, and when the process terminates the OS will clean up any open file descriptors.

Anyway, it's good practice to always close your resources when you're done, so close the streams :)

answered 2009-02-05T13:58:22.537
7

If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets.

Closing a stream also makes sure that data is flushed through the stream if there is any data left to send.

answered 2009-02-05T13:58:51.897

Your Answer