Java
BufferedReader
Learn efficient reading with BufferedReader.
Efficient reading with BufferedReader
BufferedReader reads text by buffering large chunks, so it is faster than Scanner for multi-line input. InputStreamReader wraps System.in.
import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
readLine() returns a line as a string; it returns null at end of stream. This method can throw IOException, so you add throws java.io.IOException to the main signature. You will see the details in the exceptions lessons.
Wrap System.in
System.in cannot become a BufferedReader directly; it is first wrapped with InputStreamReader. This converts a byte stream into a character stream.
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
System.out.println(line);
Read from inside out: first System.in (bytes), then InputStreamReader (characters), and on the outside BufferedReader (buffer). This three-layer structure is the foundation of Java input streams.
Exercise Read a line and print it
Create a BufferedReader (wrapping System.in with InputStreamReader), read a line with readLine and print it with println. The user will type Hello world. Add throws java.io.IOException to the main signature.
Show example solution
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
System.out.println(line);
Test yourself
-
Which method does BufferedReader use to read a line?
- nextLine()
- readLine()
- getLine()
- scanLine()
Show answer
readLine() — BufferedReader uses readLine() to read a line; nextLine belongs to Scanner.
-
Match each tool to its purpose
- Scanner
- Easy input
- BufferedReader
- Fast reading
- InputStreamReader
- Stream wrapper
- readLine()
- Returns a line
-
Create the BufferedReader
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.____));
Show answer
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
Next lesson: try-with-resources