Java PrintStream
What PrintStream Is
java.io.PrintStream is an output stream that can print values of any type as text. You've used it in every Java program: System.out and System.err are both PrintStream objects.
System.out.println("Hello"); // System.out is a PrintStream
A plain OutputStream only writes bytes. PrintStream sits on top of one and adds:
printandprintlnmethods for every primitive type,String,char[]andObject,- formatted output with
printfandformat, - conversion of characters to bytes using a charset,
- optional automatic flushing,
- no checked exceptions: errors are recorded internally instead of being thrown.
That last point is a deliberate design decision. Printing happens everywhere — debugging, logging, progress messages — and forcing every println to handle IOException would be impractical. The consequence is that PrintStream is convenient for console output but needs care when the output really matters, as this lesson shows.
Printing Values
import java.util.*;
public class P1 {
public static void main(String[] args) {
System.out.println("System.out is a " + System.out.getClass().getName());
System.out.print("no newline, ");
System.out.print(42);
System.out.println();
System.out.println(3.0 / 4);
System.out.println('A' + 1);
System.out.println("" + 'A' + 1);
char[] letters = {'J', 'a', 'v', 'a'};
System.out.println(letters);
System.out.println("letters: " + Arrays.toString(letters));
Object nothing = null;
System.out.println(nothing);
System.out.println(List.of("pen", "ink"));
System.out.printf("%-8s|%6.2f|%,d%n", "total", 1234.5, 1_000_000);
System.out.format(Locale.GERMANY, "%,.2f%n", 1234.5);
System.out.append("append ").append('x').append("\n");
}
}
Output (in an English locale):
System.out is a java.io.PrintStream
no newline, 42
0.75
66
A1
Java
letters: [J, a, v, a]
null
[pen, ink]
total |1234.50|1,000,000
1.234,50
append x
What each line shows:
| Code | Behaviour |
|---|---|
print(x) | Writes the text form of x, without a line break |
println() / println(x) | Writes x (if given) followed by the platform line separator (\n or \r\n) |
println('A' + 1) | 'A' + 1 is int arithmetic (65 + 1), so 66 is printed. Starting with "" makes it string concatenation: A1 |
println(char[]) | Has its own overload that prints the characters (Java). Any other array prints as a type code and hash, which is why Arrays.toString is used for display |
println(null object) | Prints null instead of throwing — print(Object) uses String.valueOf(obj) |
println(List.of(...)) | Calls the object's toString() |
printf / format | Formatted output using the same syntax as String.format. %-8s left-aligns in 8 characters, %6.2f gives two decimals in 6 characters, %,d adds grouping separators, %n writes the platform line separator |
format(Locale, ...) | Formats for a specific locale: German uses . for grouping and , for decimals |
append(...) | From the Appendable interface; returns the stream so calls can be chained |
Use %n rather than \n in format strings when the output should follow the platform's line-ending convention.
How print Converts Text to Bytes
A PrintStream writes bytes, so text is encoded with a charset. For System.out and System.err, Java chooses the charset from the terminal environment; since Java 19 you can read it with System.getProperty("stdout.encoding") and override it with -Dstdout.encoding=UTF-8. If a terminal is set to a charset that can't represent a character (for example the ₹ sign on an old Windows console code page), it's printed as ?. That isn't a bug in your string — it's the output encoding.
For PrintStreams you create yourself, always pass the charset explicitly.
Creating a PrintStream for a File
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class P2 {
public static void main(String[] args) throws IOException {
try (PrintStream report = new PrintStream(new FileOutputStream("report.txt"), false, StandardCharsets.UTF_8)) {
report.println("Monthly report");
report.printf("%-10s %10s%n", "Course", "Revenue ₹");
report.printf("%-10s %,10d%n", "Java", 48250);
}
System.out.print(Files.readString(Path.of("report.txt")));
PrintStream broken = new PrintStream(new OutputStream() {
@Override public void write(int b) throws IOException {
throw new IOException("disk full");
}
}, true);
broken.println("this line is lost");
System.out.println("no exception was thrown; checkError() = " + broken.checkError());
}
}
Output:
Monthly report
Course Revenue ₹
Java 48,250
no exception was thrown; checkError() = true
Constructors
| Constructor | Use |
|---|---|
new PrintStream(OutputStream out, boolean autoFlush, Charset cs) | Wrap any byte stream with an explicit charset (Java 10+) |
new PrintStream(String fileName, Charset cs) / new PrintStream(File file, Charset cs) | Create or truncate a file directly (Java 10+) |
new PrintStream(OutputStream out) | Platform default charset, no auto-flush |
Auto-flush. With autoFlush = true, the stream flushes after every println, whenever a byte array is written, and whenever a newline character is written (so a printf ending in %n is flushed too). That's what makes console messages appear immediately. For files, leaving it false is faster; closing the stream flushes everything.
Errors are swallowed
The second part of the example connects a PrintStream to an OutputStream that always fails, as a full disk or a closed network connection would. println doesn't throw. The PrintStream catches the IOException, sets an internal error flag, and carries on. The only way to find out is checkError(), which flushes the stream and returns true if any error has occurred.
That makes PrintStream (and its character-based cousin PrintWriter) a poor choice for output whose loss would matter, such as an export or a data file. Either call checkError() before closing, or use a BufferedWriter/OutputStream, which throw IOException immediately.
System.out and System.err
System.out | System.err | |
|---|---|---|
| Stream | Standard output | Standard error |
| Intended for | The program's results | Errors, warnings, diagnostics |
Redirected by > file | Yes | No (needs 2> file) |
Keeping them separate lets users redirect results to a file while still seeing error messages on screen. Because they're independent streams, their output can appear in a slightly different order on screen than the order of the calls.
Redirecting System.out
System.setOut(PrintStream) and System.setErr(PrintStream) replace the standard streams for the whole JVM. The classic use is capturing output in tests:
import java.io.*;
import java.nio.charset.StandardCharsets;
public class P3 {
static void greet(String name) {
if (name.isBlank()) {
System.err.println("warning: empty name");
return;
}
System.out.println("Hello, " + name + "!");
}
static String captureOut(Runnable code) {
PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (PrintStream capture = new PrintStream(buffer, true, StandardCharsets.UTF_8)) {
System.setOut(capture);
code.run();
} finally {
System.setOut(original);
}
return buffer.toString(StandardCharsets.UTF_8);
}
public static void main(String[] args) {
String out = captureOut(() -> greet("Asha"));
System.out.println("captured: [" + out.strip() + "]");
System.out.println("test " + (out.equals("Hello, Asha!" + System.lineSeparator()) ? "PASSED" : "FAILED"));
String none = captureOut(() -> greet(" "));
System.out.println("captured for blank name: [" + none + "]");
}
}
Output (the warning comes from System.err, which wasn't redirected):
captured: [Hello, Asha!]
test PASSED
warning: empty name
captured for blank name: []
How it works:
- Save the original
System.outbefore replacing it. - Redirect to a
PrintStreamover aByteArrayOutputStream, which collects everything printed in memory. - Run the code under test. Its
System.out.printlncalls now go into the buffer. - Restore the original in
finally, so the rest of the program prints normally even if the code throws. Forgetting this leaves the whole JVM printing into a buffer nobody reads. - Compare the captured text. The expected value uses
System.lineSeparator(), becauseprintlnwrites the platform separator —"Hello, Asha!\n"would fail on Windows.
For the blank name, nothing is written to System.out; the warning goes to System.err and appears directly on the console.
System.setOut affects every thread in the JVM, so tests that capture output shouldn't run in parallel with others that print. In real projects, a better design is to pass a PrintStream (or a Writer) into the code as a parameter, so tests can supply their own without touching global state.
Practical Example: Writing Output to the Console and a Log File
Batch jobs often need their progress messages both on screen (for whoever runs the job) and in a log file (for later investigation). A small OutputStream that forwards every byte to two destinations — a tee, named after the Unix tee command — achieves this without changing any of the job's println calls.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
public class Tee {
static class TeeOutputStream extends OutputStream {
private final OutputStream first, second;
TeeOutputStream(OutputStream first, OutputStream second) {
this.first = first;
this.second = second;
}
@Override public void write(int b) throws IOException { first.write(b); second.write(b); }
@Override public void write(byte[] b, int off, int len) throws IOException {
first.write(b, off, len);
second.write(b, off, len);
}
@Override public void flush() throws IOException { first.flush(); second.flush(); }
@Override public void close() throws IOException {
try { second.close(); } finally { first.flush(); } // never close the real console
}
}
public static void main(String[] args) throws IOException {
Path log = Path.of("job.log");
PrintStream console = System.out;
OutputStream file = Files.newOutputStream(log, CREATE, TRUNCATE_EXISTING);
try (PrintStream both = new PrintStream(new TeeOutputStream(console, file), true, StandardCharsets.UTF_8)) {
System.setOut(both);
System.out.println("import started");
System.out.printf("processed %d rows%n", 1250);
System.out.println("import finished");
} finally {
System.setOut(console);
}
System.out.println("--- job.log contains ---");
System.out.print(Files.readString(log));
}
}
Output:
import started
processed 1250 rows
import finished
--- job.log contains ---
import started
processed 1250 rows
import finished
Step by step:
TeeOutputStreamextendsOutputStream. Onlywrite(int)is required, but overridingwrite(byte[], int, int)passes whole blocks along at once instead of byte by byte, which matters for performance.flushflushes both destinations, so with auto-flush enabled each line reaches the console and the file immediately.closecloses only the file. The console stream belongs to the JVM; closing it would make every laterSystem.out.printlnin the program silently print nothing. It's only flushed. Thetry/finallyensures the flush happens even if closing the file fails.System.setOut(both)sends all standard output through the tee. The job's code doesn't change at all — it still callsSystem.out.println.- try-with-resources closes the
PrintStream, which closes the tee, which closes the log file.finallythen restores the originalSystem.out. - The log file contains exactly what was shown on screen.
For applications rather than one-off jobs, a logging framework (SLF4J with Logback or Log4j 2) is the better tool: it writes to several destinations, adds timestamps and levels, rotates files and can be configured without code changes. But knowing how PrintStream and stream wrapping work explains what those frameworks do underneath, and is the right tool for small utilities and tests.