Is there a way to check if PrintWriter is open and ready to exit without writing it?

I am looking in JavaDoc for PrintWriter, and its basic Writer(its out), and I see no way to confirm that PrintWriter is really open. While you can check null-ness, you cannot check if the stream is closed. You can also checkError(), but it closes, is really considered a mistake?

I'm not new to general Java, but java.iohas always been foggy for me. Thanks for helping.

+4
source share
1 answer

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;
    }
}
+4
source

All Articles