Vince
Vince

Reputation: 15146

Do you need to close streams if you close socket in Java?

I've heard that calling 'socket.close()' automatically closes it's streams.

Would:

public void close() {
     try {
          socket.close();
     }catch(IOException e) { }
}

Have the same effect as:

public void close() {
     try {
          outputstream.close();
          inputstream.close();
          socket.close();
     }catch(IOException e) { }
}

If your goal was to completely close the socket?

Upvotes: 5

Views: 2350

Answers (3)

user207421
user207421

Reputation: 310860

Yes, closing the input or output stream or the socket closes both streams and the socket.

However you shouldn't close the socket, you should close the outermost OutputStream or Writer you have wrapped around its output stream, so it gets flushed. Only you can do that. The socket can only close its output stream, not what you've wrapped around it.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533442

You should do this is you have a buffered output stream. This will flush any data which has not been sent yet.

Otherwise, closing the socket will close the streams so it is redundant.

Upvotes: 0

Mike B
Mike B

Reputation: 5451

Closing a socket will also close the socket's InputStream and OutputStream:

http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#close()

Upvotes: 5

Related Questions