I believe that it is best to work with the program based on the assumption that you PrintWriterare in the state you are expecting. PrintWriter- This is the type of writer that does not give you errors and is safe to write without any exceptions.
Consider the transition to another class that will cause errors when writing data, then you can catch them and determine the state of the stream.
You can always implement your own subclass. The variable outis a protected class variable PrintWriterthat, when closed, is set to zero. I based this on a method PrintWriter.ensureOpen(), this is a private method, so you need to look for it in the source to find it.
private class StatePrintWriter extends PrintWriter {
public StatePrintWriter(PrintWriter writer) {
super(writer);
}
public boolean isOpen() {
return out != null;
}
}
source
share