← Java from Scratch Lesson 63 of 88 · 10 XP

BufferedReader

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

BufferedReader reads characters as lines and keeps a buffer (8 KB), which makes it fast:

import java.io.*;

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null) {     // null — the end of the input
    …
}

try (BufferedReader f = new BufferedReader(new FileReader("a.txt"))) { … }
r.lines()   // a Stream<String> of all the lines (Java 8+)

BufferedReader is many times faster than Scanner on large volumes (Scanner parses the text with regular expressions) — that's why in competitive programming in Java, input is read with it.

Task. Read the whole input with a BufferedReader. Print the number of lines, the number of words (separated by spaces; empty lines have 0 words) and the longest word (on a tie — the first one).

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