Video in progress
What is PrintWriter, and how does it differ from BufferedWriter?
PrintWriter gives you convenient formatting methods: println, printf, format. But it does not throw IOException: errors are swallowed inside and can only be detected through checkError(). BufferedWriter throws the error openly.
📖 Answer
try (var pw = new PrintWriter(Files.newBufferedWriter(Path.of("report.txt")))) {
pw.printf("%-10s %5d%n", "Toshkent", 1200);
pw.println("---");
}
It is convenient for writing a report or a CSV. But it has one serious flaw: if the disk fills up, PrintWriter stays silent. The program thinks "I wrote it", while the file is incomplete.
if (pw.checkError()) {
throw new IOException("Fayl to'liq yozilmadi");
}
For important files I usually use BufferedWriter, or I always check checkError() at the end.
Also: new PrintWriter(outputStream) does not auto-flush by default. If you pass new PrintWriter(out, true), it flushes only on println/printf/format calls, not on a plain print.
Sign up to mark studied questions and save your progress.