Does closing the socket close the stream?

耗尽温柔 提交于 2019-12-07 06:59:49

问题


  1. I am working in a legacy java application, In many files, socket and streams are used, where sockets are getting closed but not the streams, is this necessary to close all the streams before closing the socket. because I am getting "too many open files error", is this error because of not closing the streams.....

  2. closing the socket will automatically close the streams also?


回答1:


From the Socket Javadoc:

Closing this socket will also close the socket's InputStream and OutputStream.

So generally speaking, closing the socket should be enough to close both streams it created.

Your "too many open files error" is most likely caused by something else.




回答2:


Closing any one of those closes the other two, but you should close the outermost output stream (or Writer) that you have wrapped around the socket. That closes the input stream and the socket. If you don't close the outermost output stream yourself, it won't get flushed, and so you can lose data if there is a buffered outpput stream or writer in the stack. You could also close the socket itself in a finally block to be sure: in fact lack of finally blocks may well be the cause of your problem.



来源:https://stackoverflow.com/questions/17725254/does-closing-the-socket-close-the-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!