Java ClosedWriter-class And Method Code Example
Here is an example of using the ClosedWriter class from the Apache Commons IO library in Java to create a closed Writer that throws an exception when any method is called:
import java.io.IOException;
import org.apache.commons.io.output.ClosedWriter;
public class ClosedWriterExample {
public static void main(String[] args) {
// create a new ClosedWriter
ClosedWriter closedWriter = ClosedWriter.CLOSED_WRITER;
try {
closedWriter.write("This text will not be written");
} catch (IOException e) {
System.out.println("Error writing to closed writer: " + e.getMessage());
}
}
}
In this example, the ClosedWriter.CLOSED_WRITER is used to create a new instance of a closed Writer. This can be used to ensure that a Writer is closed and no more data is written to it. When any method is called on a closed Writer, an IOException is thrown with the message "Writer is closed".
The ClosedWriter class is a simple utility class that can be useful in situations where you need to ensure that a Writer is closed and no more data is written to it.
It is a singleton class and its constructor is private, so it is not possible to create new instances, only one instance of the closed Writer is available through the CLOSED_WRITER field.