PrintWriter for formatted output
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)System.out.printf makes neat tables on the screen. PrintWriter gives you the same print, println and printf methods for any file or Writer, with one catch: it never throws an exception when writing fails.
println and printf to a file
PrintWriter is a Writer with the familiar print, println, printf and format methods. You create it on a file with a charset, new PrintWriter(file, StandardCharsets.UTF_8) (Java 10), or on another writer, such as new PrintWriter(Files.newBufferedWriter(path, UTF_8)).
Example 1 · A marks report with printf
import java.io.IOException;import java.io.PrintWriter;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class MarksReportDemo { public static void main(String[] args) throws IOException { String[] names = { "Asha", "Ravi", "Meenakshi" }; int[][] marks = { { 82, 91, 77 }, { 67, 58, 72 }, { 95, 88, 90 } };
Path dir = Files.createTempDirectory("report"); Path file = dir.resolve("report.txt"); try (PrintWriter out = new PrintWriter(file.toFile(), StandardCharsets.UTF_8)) { out.println("Class 12 B - Unit test 1"); out.printf("%-10s %5s %7s%n", "Name", "Total", "Average"); for (int i = 0; i < names.length; i++) { int total = marks[i][0] + marks[i][1] + marks[i][2]; out.printf("%-10s %5d %7.1f%n", names[i], total, total / 3.0); } }
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) { System.out.println(line); } Files.delete(file); Files.delete(dir); }}Class 12 B - Unit test 1 Name Total Average Asha 250 83.3 Ravi 197 65.7 Meenakshi 273 91.0
What this code does
%-10spads each name to 10 characters on the right and%5dpads each total on the left, so the columns line up in the file.%7.1frounds the average to one decimal place. The program reads the file back withFiles.readAllLinesto show exactly what was written.
printf uses format codes: %-10s is text left-aligned in 10 spaces, %5d a whole number right-aligned in 5, %6.1f a decimal with 1 digit after the point, and %n a line break. %n writes the line separator of the computer the program runs on: \r\n on Windows, \n on macOS and Linux.
printf formats numbers for the computer's language settings, so some regions print 82,5 instead of 82.5. For files that other programs read, pass Locale.ROOT as the first argument: out.printf(Locale.ROOT, "%.1f%n", avg).Auto flush
Auto flush makes a PrintWriter flush after every println, printf and format call. Turn it on with the second constructor argument: new PrintWriter(writer, true).
print does not trigger it, so text written with print waits until the next println, an explicit flush() or close().
Example 2 · Auto flush: println flushes, print does not
import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class AutoFlushDemo { static int linesOnDisk(Path file) throws IOException { return Files.readAllLines(file, StandardCharsets.UTF_8).size(); }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("autoflush");
Path quiet = dir.resolve("quiet.log"); try (PrintWriter out = new PrintWriter(new FileWriter(quiet.toFile(), StandardCharsets.UTF_8))) { out.println("TXN1 Rs 250"); System.out.println("Auto flush off, after println: " + linesOnDisk(quiet) + " lines on disk"); }
Path live = dir.resolve("live.log"); try (PrintWriter out = new PrintWriter(new FileWriter(live.toFile(), StandardCharsets.UTF_8), true)) { out.println("TXN1 Rs 250"); System.out.println("Auto flush on, after println: " + linesOnDisk(live) + " lines on disk"); out.print("TXN2 Rs 99 "); System.out.println("Auto flush on, after print: " + linesOnDisk(live) + " lines on disk"); out.println("OK"); System.out.println("Auto flush on, after println: " + linesOnDisk(live) + " lines on disk"); }
Files.delete(quiet); Files.delete(live); Files.delete(dir); }}Auto flush off, after println: 0 lines on disk Auto flush on, after println: 1 lines on disk Auto flush on, after print: 1 lines on disk Auto flush on, after println: 2 lines on disk
What this code does
- Without auto flush, the line waits in the buffer inside
FileWriter, so the file is still empty while the program runs. - With auto flush on, each
printlnpushes its line to the file at once. Theprintcall did not flush; its text reached the disk together with the nextprintln.
Auto flush suits a log or a progress file that another program watches while yours runs. For a report written in one go, leave it off and let close flush once; flushing after every line is slower.
PrintWriter hides errors: checkError
PrintWriter methods never throw IOException. If the disk is full or the file is gone, the method catches the error, sets an internal flag and returns as if all went well.
Example 3 · A full disk that PrintWriter does not report
import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.Writer;import java.nio.charset.StandardCharsets;
class FullDisk extends OutputStream { // pretends the disk is full after 20 bytes private int used = 0;
@Override public void write(int b) throws IOException { if (used >= 20) { throw new IOException("No space left on device"); } used++; }}
public class CheckErrorDemo { public static void main(String[] args) { PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FullDisk(), StandardCharsets.UTF_8)); pw.println("Asha,82,Pass"); pw.println("Ravi,67,Pass"); pw.println("Meena,91,Pass"); System.out.println("PrintWriter: no exception was thrown"); System.out.println("checkError(): " + pw.checkError()); pw.close();
try (Writer w = new BufferedWriter(new OutputStreamWriter(new FullDisk(), StandardCharsets.UTF_8))) { w.write("Asha,82,Pass\nRavi,67,Pass\nMeena,91,Pass\n"); w.flush(); System.out.println("BufferedWriter: saved"); } catch (IOException e) { System.out.println("BufferedWriter threw: " + e.getMessage()); } }}PrintWriter: no exception was thrown checkError(): true BufferedWriter threw: No space left on device
What this code does
FullDiskthrowsIOExceptionafter 20 bytes, like a full disk. The threeprintlncalls still returned normally; onlycheckError()reveals that the data was not saved.- The same data written through a
BufferedWriterthrows theIOException, so the program cannot miss the failure.
checkError() flushes the writer and returns true if any error has happened so far. Call it after writing something important, and treat true as a failed write. This makes PrintWriter easy to use in small programs and risky for data that must not be lost. When you need every error reported, write with a BufferedWriter, whose methods do throw IOException.
System.out is a PrintStream
PrintStream is the byte-stream twin of PrintWriter: it also has print, println and printf, encodes the text into bytes, and hides errors behind checkError(). System.out and System.err are both PrintStream objects.
Example 4 · System.out is a PrintStream you can redirect
import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.nio.charset.StandardCharsets;
public class CaptureOutputDemo { static void printTicket(String name, String pnr) { System.out.println("Passenger: " + name); System.out.printf("PNR: %s%n", pnr); }
public static void main(String[] args) { System.out.println("System.out is a " + System.out.getClass().getName());
PrintStream original = System.out; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer, true, StandardCharsets.UTF_8)); try { printTicket("Kabir", "4521983"); } finally { System.setOut(original); }
String captured = buffer.toString(StandardCharsets.UTF_8); System.out.println("Captured " + captured.lines().count() + " lines"); System.out.println("Has the PNR: " + captured.contains("PNR: 4521983")); }}System.out is a java.io.PrintStream Captured 2 lines Has the PNR: true
What this code does
- While
System.outpoints at theByteArrayOutputStream, the two lines thatprintTicketprints go into the buffer instead of the screen. - The
finallyblock puts the originalSystem.outback even if the method throws, so the last lines appear on the screen again.
System.setOut(...) replaces System.out with your own PrintStream. Pointing it at a ByteArrayOutputStream captures everything a method prints, which is handy for testing code that prints. Always keep the original and put it back afterwards, or the rest of the program prints into your buffer.
Next step
Check your understanding
11 quick questions