Reputation: 47
When using Scanner/ PrintWriter to manipulate those streams, do we need to close them explicitly or does closing the socket, close the Scanner and PrintWriter objects as well?
Upvotes: 0
Views: 38
Reputation: 3669
Most of the java IO classes use 'Decorator' pattern to wrap the raw types. Closing a socket object directly will not close the Scanner/PrintWriter, but closing Scanner/Printwrite will cascade the operation to under laying raw type.
If you close Socket directly, then the code which depends on 'Scanner/Printwriter' may get unexpected results.
Most of the Decorated classes, provide wrapped type methods and cascade the operation, but it is always better to check the source of Decorated class.
In case of 'PrintWriter', it invokes 'close' on writer object.
public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
}
And flush() will not close the stream, but makes sure that everything in buffer is written to the target.
Upvotes: 1