What is the difference between closing Input/OutputStream and closing Socket directly?

From the java api documentation for Socket:

public void close()
throws IOException
Closes this socket.
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.

Once a socket has been closed, it is not available for further networking use (i.e. can’t be reconnected or rebound). A new socket needs to be created.

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

If this socket has an associated channel then the channel is closed as well.

Closing the InputStream of the Socket will lead to the closing of the Socket. The same goes for closing the OutputStream of the Socket.

From the java api documentation for Socket#getInputStream()

Closing the returned InputStream will close the associated socket.

Check the API documentation, it is there for a reason.

Leave a Comment