Auto-Flushing and checkError
You'll learn how PrintWriter decides when to automatically flush its buffer and how to detect I/O errors without dealing with exceptions.
Unlike most character streams, PrintWriter has a special feature: auto-flushing. When you create a PrintWriter, you can enable this behavior so that certain write operations automatically call flush(), pushing buffered data to disk immediately.
When Auto-Flushing Happens
Auto-flushing is enabled through specific constructors, typically when wrapping an OutputStream. When enabled, PrintWriter automatically flushes in these situations:
- After calling
println()(but not afterprint()) - After calling
printf()orformat()with a newline character - Writing a newline character (
\n) in the output
Think of auto-flushing like an automatic save feature in a text editor—it ensures your data reaches its destination at predictable moments without explicit flush() calls.
// Auto-flush enabled (second parameter is true)
PrintWriter pw = new PrintWriter(
new FileOutputStream("log.txt"), true);
pw.println("This line flushes automatically");
pw.print("This does NOT auto-flush");
pw.printf("Count: %d%n", 42); // Flushes because of %n
The checkError Method
PrintWriter never throws IOException during write operations—it silently catches them. To detect if an error occurred, use checkError():
pw.println("Critical data");
if (pw.checkError()) {
System.err.println("Write operation failed!");
}
Once checkError() returns true, it stays true for the lifetime of that PrintWriter. There's no way to reset the error state.
Key Takeaway:
Enable auto-flushing when creating PrintWriter to automatically flush after println() calls, and use checkError() to detect I/O errors since PrintWriter suppresses exceptions.