closing the streams of I/o

2019-05-15 20:22发布

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.

标签: java stream io
3条回答
趁早两清
2楼-- · 2019-05-15 20:57

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.

查看更多
爷的心禁止访问
3楼-- · 2019-05-15 20:59

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.

查看更多
相关推荐>>
4楼-- · 2019-05-15 21:08

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

查看更多
登录 后发表回答