I'm looking in the JavaDoc for both PrintWriter
, and its underlying Writer
(its out
field), and I don't see any way to confirm that the PrintWriter is indeed open. While you can test for null
-ness, you can't test to see if the stream has been closed. You can also checkError()
, but is being closed really considered an error?
I'm not a newbie to general Java, but java.io
has always been hazy to me. Thank you for helping.
I think its best to work your program flow around basing assumptions that the PrintWriter
is in the state you expect. The PrintWriter
is a type of writer that does not give you errors and is safe to write with no exceptions thrown.
Consider moving to a different class that will throw you errors when writing data, you can then catch those and determine the state of the stream.
You can always implement your own subclass. The variable out
is a protected variable of the PrintWriter
class that is set to null when closed. I based this off the method PrintWriter.ensureOpen()
it is a private method so you have to look in the source to find it.
private class StatePrintWriter extends PrintWriter {
public StatePrintWriter(PrintWriter writer) {
super(writer);
}
public boolean isOpen() {
return out != null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With