Command Palette

Search for a command to run...

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

readLine with mixed line endings

\n, \r\n and a lone \r all end a line, and none of them appear in the result. An empty line is "", not null.

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?

readLine with mixed line endings
Sign in to run this example in your browser.

Expected output

1: [first] length 5
2: [second] length 6
3: [] length 0
4: [fourth] length 6
5: [last without newline] length 20
after the end: null