4

What are the bad things that can happen when I don't close the stream?

Does the close operation automatically flush?

Are all the streams closed after the program exits?

Thanks in advance.

Junuxx
  • 14,011
  • 5
  • 41
  • 71
saravanan
  • 5,339
  • 7
  • 45
  • 52
  • See this post, it has the similar question with some good answers. http://stackoverflow.com/questions/515975/closing-streams-in-java – Mudassir Mar 01 '11 at 13:26

3 Answers3

8

Bad things that can happen when you don't close your streams:

  • you can run out of file handles
  • data that you think is written to disk may still be in the buffer (only)
  • files might still be locked for other processes (depends on the platform)
  • ...

Yes, close operation always flushes the stream.

All file handles that the OS is aware of are closed. This means effectively that FileOutputStream, FileInputStream and the input/output of a Socket will be closed. But if you wrap a FileOutputStream in a BufferedOutputStream then that BufferedOutputStream will not be known to the OS and won't be closed/flushed on shutdown. So data written to the BufferedOutputStream but not yet flushed to the FileOutputStream can be lost.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • SO ALL streams are closed automatically when the program exits..close operation flushes automatically ..so i am safe isn't it – saravanan Mar 01 '11 at 13:35
  • Actually: I've not been entirely correct. I edited my answer. – Joachim Sauer Mar 01 '11 at 13:35
  • 1
    why FileInputStream and OutputStream are only known to os ..why not BufferedOutputStream – saravanan Mar 01 '11 at 13:42
  • @saravanan: `File*Stream` represent direct OS resources (namely open file handles). A `BufferedOutputStream` is a pure Java object that wraps another output-stream. There's no need for the OS to know of its existance. – Joachim Sauer Mar 01 '11 at 13:44
  • What happens if the stream goes out of scope? May all resources be recollected, including the file handles, by the GC? – poitroae Aug 08 '13 at 21:30
3

1) You tie up system resources unnecessarily (e.g. file descriptors). Possibly to the extent of running out of them.

2) Yes (although you should check the documentation of the particular stream you're interested in to be sure).

3) Yes

dty
  • 18,795
  • 6
  • 56
  • 82
  • In the project I'm working previous person, was not closing file descriptors, after few days of running there were thousands of exceptions :D – Serhiy Mar 01 '11 at 13:28
1

To qualify, when you perform a close(), it flushes the data and closes the file handle. If you exit, the file handle is closed but un-flushed data is lost.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130