All 15 I/O & NIO questions
More in I/O & NIO
Advertisement
Java › I/O & NIO

What is the purpose of the PrintStream and PrintWriter classes (like System.out), and how do they differ from lower-level OutputStream/Writer in their exception-handling behavior?

Intermediate

Answer

PrintStream (System.out is one) and PrintWriter provide convenient formatted-output methods (print(), println(), printf()) for a wide variety of types, and notably NEVER throw checked IOException from their write methods -- instead, any underlying I/O error sets an internal error flag (checkable via checkError()) that calling code can optionally inspect, rather than requiring every single print statement throughout a codebase to be wrapped in a try-catch or declare a checked exception, a deliberate ergonomic trade-off making these classes convenient for everyday console/simple output use, at the cost of making I/O failures easier to silently miss if checkError() is never actually consulted.
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
writer.println("Hello");  // no checked exception to handle, unlike a raw Writer's write() method
writer.printf("Value: %d%n", 42);

if (writer.checkError()) {  // must be explicitly checked -- easy to forget!
    System.err.println("An I/O error occurred during writing, but was silently absorbed");
}
writer.close();
Real-world example A logging utility built on PrintWriter for its ergonomic printf()-style formatting occasionally silently loses log entries during a disk-full scenario, since the code never called checkError() to detect the internally-flagged write failures, an important design consideration when choosing PrintWriter's convenience over a lower-level Writer that would have forced explicit exception handling.

Common follow-ups: Why did the JDK designers choose to suppress checked exceptions specifically for PrintStream/PrintWriter but not other I/O classes?;What's the relationship between System.out (a PrintStream) and redirecting console output to a file via System.setOut()?