PrintStream Class in Java: print, println and printf
Every Java developer has used PrintStream, often without knowing it: System.out and System.err are PrintStream objects. The same class can print text to files, sockets or memory, with the familiar print(), println() and printf() methods.
This tutorial covers the class, its constructors and methods, its unusual error handling and when to prefer PrintWriter.
1. What Is PrintStream in Java?
PrintStream is a filter output stream that turns values of any type, such as numbers, booleans and objects, into their text form and writes them as bytes, using a charset. It has two special features:
- It never throws
IOException. Errors set an internal flag that you check withcheckError(). - It can flush automatically after
println(), after writing a byte array, or when a newline is written.
2. PrintStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of PrintStream
| Constructor | Description |
|---|---|
PrintStream(OutputStream out) | Prints to another stream, without automatic flushing. |
PrintStream(OutputStream out, boolean autoFlush, Charset charset) | Adds automatic flushing and an explicit charset (Java 10). |
PrintStream(String fileName) / PrintStream(File file) | Prints to a file, replacing its content (Java 5). |
PrintStream(File file, Charset charset) | Prints to a file with an explicit charset (Java 10). |
4. Commonly Used Methods
| Method | Description |
|---|---|
print(x) / println(x) | Prints any primitive, String, char[] or object; println adds a line separator. |
printf(format, args...) / format(...) | Formatted output, such as "%.2f" (Java 5). |
append(CharSequence csq) | Appends text; returns the stream for chaining (Java 5). |
checkError() | Flushes and returns true if any error has occurred. |
writeBytes(byte[] buf) | Writes raw bytes (Java 14). |
charset() | Returns the charset used to encode characters (Java 18). |
5. Example: Printing an Invoice to a File
An electronics shop prints invoices to text files. printf() aligns the columns, and an explicit charset makes the file predictable.
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
public class InvoicePrinter {
public static void main(String[] args) throws IOException {
Path invoice = Files.createTempFile("invoice", ".txt");
String[] items = {"Keyboard", "Mouse", "USB-C cable"};
double[] prices = {1899.0, 649.5, 299.0};
try (PrintStream out = new PrintStream(invoice.toFile(), StandardCharsets.UTF_8)) { // Java 10
out.println("INVOICE #2026-118");
double total = 0;
for (int i = 0; i < items.length; i++) {
out.printf(Locale.ROOT, "%-12s %9.2f%n", items[i], prices[i]);
total += prices[i];
}
out.printf(Locale.ROOT, "%-12s %9.2f%n", "TOTAL", total);
System.out.println("Charset used: " + out.charset()); // Java 18
}
System.out.print(Files.readString(invoice));
Files.delete(invoice);
}
}
Charset used: UTF-8 INVOICE #2026-118 Keyboard 1899.00 Mouse 649.50 USB-C cable 299.00 TOTAL 2847.50
How the code works
new PrintStream(file, StandardCharsets.UTF_8)(Java 10) opens the file with an explicit charset.%-12sleft-aligns the item name in 12 characters, and%9.2fright-aligns the price with two decimals.Locale.ROOTkeeps the decimal point as., whatever the computer's regional settings are.charset()(Java 18) confirms the charset in use.
6. Example: Errors Do Not Throw Exceptions
An order service writes notifications through a PrintStream. Here the destination always fails, like a full disk. The failure does not reach the caller as an exception.
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class SilentFailure {
public static void main(String[] args) {
// A destination that always fails, like a full disk or a closed socket
OutputStream broken = new OutputStream() {
@Override
public void write(int b) throws IOException {
throw new IOException("disk full");
}
};
PrintStream out = new PrintStream(broken);
boolean thrown = false;
try {
out.println("Order 501 shipped"); // the write fails inside PrintStream...
out.flush();
} catch (RuntimeException e) {
thrown = true;
}
System.out.println("Exception thrown: " + thrown); // ...but nothing reaches the caller
System.out.println("checkError(): " + out.checkError());
}
}
Exception thrown: false checkError(): true
How the code works
- The anonymous
OutputStreamthrows anIOExceptionfor every byte. println()catches that exception internally and only records that an error happened.checkError()returnstrue, which is the only way to learn about the failure.
This makes PrintStream convenient for console output, but risky for data that must not be lost. Call checkError() when it matters.
7. PrintStream vs PrintWriter
| Aspect | PrintStream | PrintWriter |
|---|---|---|
| Family | Byte stream (OutputStream) | Character stream (Writer) |
| Typical use | System.out, console and logging | Writing text files and responses |
| Raw bytes | Can write bytes as well as text | Text only |
| Error handling | No exceptions; checkError() | No exceptions; checkError() |
For new text output, PrintWriter is usually the better fit.
8. Common Mistakes and Best Practices
- Assuming writes succeeded. Check
checkError()for important output. - Relying on the default charset. Pass a
Charsetto the constructor. - Using locale-sensitive formats in files. Pass
Locale.ROOTtoprintffor machine-readable numbers. - Closing
System.out. Later console output would be lost.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | PrintStream with print()/println(). |
| Java 5 | printf(), format(), append() and file constructors. |
| Java 10 | Constructors that take a Charset. |
| Java 14 | writeBytes(byte[]). |
| Java 18 | charset(); UTF-8 becomes the default charset (JEP 400). |
| Java 25 | No API changes. The new java.lang.IO.println() offers simple console output for beginners. |
10. Summary
PrintStreamprints values as text bytes;System.outis one.- It offers
print,printlnandprintf, and can flush automatically. - It never throws
IOException; usecheckError()to detect failures. - Pass a charset explicitly, and prefer
PrintWriterfor new text output.