← Java from Scratch Lesson 64 of 88 · 10 XP

BufferedWriter

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

BufferedWriter collects text in a buffer and writes it in big pieces:

try (BufferedWriter w = new BufferedWriter(new FileWriter("report.txt"))) {
    w.write("Report");
    w.newLine();               // a line break, the way the system does it
    w.write(String.valueOf(42));
}   // close() runs flush() by itself — it flushes the buffer to the file

Without close()/flush() the last lines stay in memory and never reach the file — a common mistake.

The same goes for printing to the screen: with a lot of output, System.out.println in a loop is slow; it's faster to collect everything in a StringBuilder or to write through PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))).

Task. Read n and write an n × n multiplication table to the file table.txt with a BufferedWriter (the numbers in a line separated by spaces). Then read the file back and print it, and on the last line print the size of the file in bytes.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.