What is PrintWriter in Java, how does it differ from PrintStream, and why do both hide IOException behind checkError()?
answer
- Writer versus OutputStream
- raw bytes only on one side
- auto-flush triggers differ
- a BufferedWriter hides in one constructor
- a private sticky flag, no cause
basics
~20 sPrintWriter is a character Writer that prints formatted text; PrintStream is a byte OutputStream that encodes it. Neither throws IOException from its print methods: failures set a private flag that checkError() reports, so output calls stay free of try/catch.
solid answer
~50 s`PrintWriter` is a `Writer` with the same `print`, `println`, `printf` and `format` methods as `PrintStream`, but it works in characters and has no way to write raw bytes; `PrintStream` is an `OutputStream` that encodes text and also passes bytes through. With auto-flush on, `PrintWriter` flushes only on `println`, `printf` and `format`, while `PrintStream` flushes on `println`, a newline or any byte array written, and in the JDK's implementation, though not in the `print` Javadoc, a plain `print` flushes too, because the encoded text comes back as a byte array. `new PrintWriter(OutputStream)` also adds a `BufferedWriter`, so text can sit there until a flush or close. Neither throws `IOException` from those methods: they catch it, set a private `trouble` flag and drop the exception. `checkError()` flushes and reads the flag, so you learn that something failed but never what. The Javadoc gives no motive; convenient printing is the usual reading.
code
java · 16 linesimport java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
class Report {
static void write(Path file, int total) throws IOException {
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8))) {
out.printf("total=%d%n", total);
if (out.checkError()) {
throw new IOException("could not write " + file);
}
}
}
}go deeper
Recall that PrintStream is a byte stream and PrintWriter a character stream, both with print, println and printf. Remember that neither throws IOException from those methods, and that a PrintWriter on a file must be closed.
Explain the mechanics: what each write(int) produces, where the charset comes from, which calls trigger auto-flush, why PrintWriter over a stream holds text in a BufferedWriter, and how checkError() flushes and reads a sticky flag.
Show the production judgment: a silent disk-full error loses data unless someone reads checkError(), the flag carries no cause, and a wrapper can hide output behind a buffer. Choose a throwing writer where a lost write matters.
Treat it as a team default: allow print classes for console and diagnostics, require a throwing writer or a checked checkError() for data output, and state which charset every output uses instead of inheriting one.
## Two printers on two sides of java.io `java.io` has byte streams (`OutputStream`) and character streams (`Writer`). Each side has a printing class with `print`, `println`, `printf` and `format`: - **`PrintStream`** extends `FilterOutputStream`, so it is a byte stream. Its print methods encode text into bytes, and its `write` methods pass bytes through untouched. `System.out` is one. - **`PrintWriter`** extends `Writer`, so it is a character stream. Its Javadoc says it has no methods for writing raw bytes. | Aspect | `PrintStream` | `PrintWriter` | |---|---|---| | Type | `OutputStream` (bytes) | `Writer` (characters) | | `write(0xE9)` | One raw byte, `0xE9` | The character `é`, encoded later | | Charset | Fixed at construction, reported by `charset()` | None over a `Writer`; chosen when built over a stream or file | | Own text buffer | Encoded bytes go to the wrapped stream on each print | `BufferedWriter` when built over a stream or file; none over a `Writer` | | Auto-flush | Documented: `println`, newline, byte arrays; in the JDK's code also any `print` of text | `println`, `printf`, `format` only | | On `IOException` | Sets `trouble` | Sets `trouble` | ## Encoding A `PrintStream` converts characters with the charset you gave it; without one, it takes the charset of a `PrintStream` it wraps, or else `Charset.defaultCharset()`, which is UTF-8 since JDK 18 unless configured otherwise. Over UTF-8, `print('é')` emits two bytes and `write(0xE9)` emits one raw byte. A `PrintWriter` over a `Writer` does no encoding: that belongs to the wrapped writer, and over a `StringWriter` there are no bytes at all. Its `OutputStream` and file constructors build a `BufferedWriter` over an `OutputStreamWriter`, which encodes. Two details are worth knowing: - Wrapping a `PrintStream` in either class keeps its charset: `new PrintWriter(System.out)` and `new PrintStream(System.out)` take `System.out.charset()`. - Both classes document that they replace malformed and unmappable input with the charset's replacement string. When the class builds the encoder itself, `café` in US-ASCII prints as `caf?` and no error is recorded; a writer you pass in keeps its own policy. ## When auto-flush fires Auto-flush is a constructor flag, off unless you ask for it. - **`PrintStream`** documents three triggers: a byte array is written, a `println` runs, or a newline character or byte is written. The `print` Javadoc says text is written "in exactly the manner of" `write(int)`, which flushes only on a newline, but the JDK's implementation writes encoded byte arrays back through the stream itself, so `print("a")` and `printf("a")` flush as well. Rely on the documented triggers. A `write(int)` of any other byte does not flush. - **`PrintWriter`** flushes on `println`, `printf` and `format`, whether or not the output has a newline. `print("a\n")`, `write` and `append` do not flush. - **Without auto-flush**, `PrintStream` still hands bytes to the wrapped stream on each print, and only that stream's own buffering can delay them. `PrintWriter` over a stream or file keeps them in its `BufferedWriter`, so even `println` reaches nothing until a flush, a close or a full buffer. A file that stays empty because nobody closed the writer is the classic bug. ## Why IOException disappears Each print, write, flush and close method ends in `catch (IOException x) { trouble = true; }`. The `trouble` field is a private boolean and the exception object is discarded. `checkError()` then works in this order: 1. If the stream is still open, it calls `flush()`, which can itself set the flag. 2. If it wraps another printer, it returns that object's `checkError()` instead: a `PrintStream` asks a wrapped `PrintStream`, and a `PrintWriter` asks a wrapped `PrintWriter` or the `PrintStream` it was built on. 3. Otherwise it returns its own flag. What follows from that design: - **The flag is sticky.** Later successes do not clear it, and reading it clears nothing; only the protected `clearError()` resets it, so only a subclass can. - **You learn that something failed, never what.** There is no message or cause to read. The silence covers I/O only: - A bad format string still throws `IllegalFormatException`, and a `null` format still throws `NullPointerException`. - `PrintWriter` and `PrintStream` constructors that open a file can throw `FileNotFoundException`. - `PrintStream.write(byte[])` declares `IOException` but never throws it. `writeBytes(byte[])`, since JDK 14, exists so callers can skip the `catch`. - Printing after `close()` throws nothing and sets the flag, though a `PrintWriter` built on a `PrintStream` reports that stream's state instead, so it hides this one. The Javadoc states this behaviour but not a motive. The first sentence of `PrintStream`'s Javadoc promises printing "conveniently", and the usual reading is that `println` in every method would otherwise need a `try` block, and that diagnostics should not bring a program down. The cost is that the check is easy to forget. ## Version note JDK 26 changed one case. If a write to the wrapped stream throws `InterruptedIOException`, JDK 27 sets the flag like any other `IOException`. JDK 25 instead sets the thread's interrupted status and leaves the flag alone, so `checkError()` can still return `false`. ## Choosing - **Console and diagnostics:** `PrintStream`, as `System.out` already is. - **Mixing raw bytes and text:** `PrintStream`, since only it can do both. - **Text you format:** `PrintWriter`, including capturing a stack trace through `printStackTrace(new PrintWriter(stringWriter))`. - **Data you cannot lose:** a `BufferedWriter`, which throws, or a `PrintWriter` whose `checkError()` you read before treating the output as written.
- Can a subclass of PrintWriter recover the IOException that a failed write threw?Not by overriding `setError()`. The catch blocks assign the private `trouble` field directly and drop the exception, so `setError()` is never called on that path. To keep the cause, wrap the target in your own `Writer` that records the exception before rethrowing it, or write through a `BufferedWriter`, which throws.
- Why does new PrintWriter(socket.getOutputStream()) with println() appear to send nothing?That constructor adds a `BufferedWriter` and leaves auto-flush off, so `println` stays in memory. Use `new PrintWriter(out, true)` or call `flush()`. Also, `println` writes `System.lineSeparator()`, so a protocol that requires CRLF should write its line endings itself.
- What happens to the encoding and error state when you wrap System.out in a PrintWriter?The constructor sees a `PrintStream` and takes its `charset()`, so the encoding matches. It also saves the stream, and `checkError()` returns that stream's answer instead of its own flag, so a failure the writer records itself, such as printing after `close()`, does not show. It still adds a `BufferedWriter`, so without auto-flush or an explicit `flush()` the text waits in that buffer, and closing the writer to flush it would also close `System.out`.
- How does an unmappable character behave when a PrintWriter wraps Files.newBufferedWriter?Differently from the file constructors. `Files.newBufferedWriter` uses an encoder that reports errors, so writing `café` in US-ASCII raises an `IOException` inside the wrapped writer. `PrintWriter` catches it, so nothing is thrown, the flag is set and `checkError()` returns `true`. With `new PrintWriter(stream, true, US_ASCII)` you get `caf?` and no flag.
checkError() is a car's check-engine light: the car keeps driving when something fails, the light says that something is wrong but not what, and it stays on until a mechanic resets it, which is the job of the protected clearError().
- PrintWriter can write raw bytes through write(int), exactly as PrintStream does.
- A PrintStream with auto-flush on never flushes on write(byte[]) without a newline.
- A PrintWriter with auto-flush on flushes whenever its text contains a newline.
- checkError() hands you the IOException that caused the failure.
- Calling checkError() clears the flag, so the next call reports only new failures.
- Only PrintStream swallows IOException; PrintWriter's println throws it.
- PrintWriter
- Java 1.1
- PrintStream
- Java 1.0
- PrintStream.charset()
- Java 18
- InterruptedIOException marks the stream in error
- Java 26
Assumes JDK 27; since JDK 26 an InterruptedIOException sets the error flag, while JDK 25 sets the thread's interrupted status instead.
context
- PrintWriter (Java SE 27 & JDK 27)docs.oracle.com
- PrintWriter.java at jdk-27-gagithub.com
- PrintStream.java at jdk-27-gagithub.com