CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
  public static void main(String[] args) throws java.io.IOException {
    // Create a BufferedReader, read a line, print it
  }
}

Sample solution

Main.java
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
System.out.println(line);

Expected output

Hello world

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method does BufferedReader use to read a line?

  • nextLine()
  • readLine() Correct answer
  • getLine()
  • scanLine()

Explanation: BufferedReader uses readLine() to read a line; nextLine belongs to Scanner.

2 Match each tool to its purpose

Term Meaning
Scanner Easy input
BufferedReader Fast reading
InputStreamReader Stream wrapper
readLine() Returns a line

3 Create the BufferedReader

Question
BufferedReader reader =
  new BufferedReader(new InputStreamReader(System.____));
Answer
BufferedReader reader =
  new BufferedReader(new InputStreamReader(System.in));

Explanation: System.in is the console input, wrapped by InputStreamReader.

All lessons in Beginner