Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test if a PrintWriter is open and ready for output, without writing to it?

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.

like image 731
aliteralmind Avatar asked Jan 09 '14 19:01

aliteralmind


1 Answers

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;
    }
}
like image 131
ug_ Avatar answered Sep 24 '22 10:09

ug_