Command Palette

Search for a command to run...

Back to the lesson: Topic 12.2 — Buffered Readers and Writers
Core Java · Example 2 of 5 Java 11+

Count the trips to the source

Buffered: 8192 + 8192 + 3616 characters, then one call that returns -1. With a FileReader, each source call can be a system call.

BufferedReader and BufferedWriter put an in-memory array between your code and the real source, so thousands of tiny reads or writes become a few big ones. BufferedReader also gives you readLine() and lines(), the standard way to read text line by line.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Read "apple\n\nbanana\ncherry\n" with a BufferedReader and print how many lines there are, how many are blank, and the longest line.

02

Write a method void writeTable(Writer out, String[] names, int[] scores) that prints aligned rows with PrintWriter (names left-aligned in 8 characters, scores right-aligned in 4). Test it with a StringWriter and print the result.

03

Using BufferedReader.lines(), count the words in a multi-line string, ignoring blank lines and extra spaces.

Explain it without notes

01

Why is buffered I/O faster, and what exactly does the buffer save?

02

How does readLine() treat line terminators, empty lines and the last line?

03

What's the difference between flush() and close(), and why do output files end up empty?

04

When would you choose Scanner over BufferedReader, and what are its pitfalls?

Count the trips to the source Java 11+
Sign in to run this example in your browser.

Expected output

unbuffered: 20000 chars, 20001 calls to the source
buffered:   20000 chars, 4 calls to the source