Closing streams

HiIf I have a socket with an inputstream (BufferedReader) and outputstream (PrintWriter), will closing either or both of these streams close the underlying sockets? Will closing the underlying socket close the streams?I get a bit confused by this as I am used to C sockets.
[294 byte] By [invictus2a] at [2007-11-26 18:18:26]
# 1
My rule of thumb in those situations is that if the class directly provides or inherits a close() method then it's best to explicitly call that method to close the respective resource.
paternostroa at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...
# 2
Yeah, but the question is also whether or not the close() method replace _or_ extend the underlying close method.
invictus2a at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...
# 3

From the InputStream class javadocs for the close() method:

Closes this input stream and releases any system resources associated with the stream.

Closing either of the streams should close the socket as well however I'd advocate the explicit release of all resources.

paternostroa at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...
# 4

But if I were to create a program that first open an input stream, read some data, close the input stream, open an output stream, send som data, and finally close the outputstream...then this scheme would be a bit weird? So I am forced to keep the streams open untill the socket are to be closed?

invictus2a at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...
# 5

> So I am forced to keep the streams open

> untill the socket are to be closed?

It would appear so. However there are two methods of the Socket class which may alternatively be used instead of closing the streams. Have a look at the shutdownInput() and shutdownOutput() methods. The javadocs for shutdownInput() follows:

Places the input stream for this socket at "end of stream". Any data sent to the input stream side of the socket is acknowledged and then silently discarded.

paternostroa at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...
# 6

> But if I were to create a program that first open an

> input stream, read some data, close the input stream,

Why? Why do you need to close the input stream?

> open an output stream, send som data, and finally

> close the outputstream...

Now this makes sense.

Contrary to what's suggested above, the best way to close a socket is to close its output stream. That ensures that any final flush() occurs and it closes the input stream and the socket too. You don't need to close the input stream or the socket explicity if you do this and therefore you don't need to code the two extra try-catch blocks that would be needed if you were to code those extra closes properly.

ejpa at 2007-7-9 5:52:06 > top of Java-index,Core,Core APIs...