Sub topic 12
BufferedReader as an Alternative
This chapter assumes that you know Java classes, methods, variables, control flow, String, primitive types, and basic exception handling. It also assumes that you can compile and run a Java program from the command line.
BufferedReader reads character data efficiently, one line at a time. It is useful when your program mainly needs complete lines and does not need Scanner's built-in methods for numbers and tokens.
Connecting BufferedReader to standard input
System.in is a byte stream. A BufferedReader reads characters, so Java needs an adapter between the two:
InputStreamReaderconverts bytes fromSystem.ininto characters.BufferedReaderadds buffering and thereadLine()method.
The usual construction is:
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));A buffer is a temporary area in memory. The reader can collect a group of characters at once instead of requesting every character separately.
Reading lines and detecting end of input
readLine() returns the next line without its line-ending characters. Its return type is String, but it can return null when the input ends.
In a terminal, end of input is usually sent with Ctrl-D on Linux and macOS, or Ctrl-Z followed by Enter on Windows. A redirected file also produces null after its final line.
The following program reads a name and an age. Both values arrive as text, so the age must be converted with Integer.parseInt.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedInputDemo {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Name: ");
String name = reader.readLine();
if (name == null) {
System.out.println("No name was provided.");
return;
}
System.out.print("Age: ");
String ageText = reader.readLine();
if (ageText == null) {
System.out.println("No age was provided.");
return;
}
int age = Integer.parseInt(ageText.trim());
System.out.println(name + " is " + age);
} catch (IOException exception) {
System.err.println("Could not read input: "
+ exception.getMessage());
} catch (NumberFormatException exception) {
System.err.println("Age must be a whole number.");
}
}
}IOException is a checked exception. It represents an input or output failure, such as a disconnected stream. This example handles it with catch. An alternative is to declare throws IOException on main.
trim() removes whitespace at the beginning and end of the age text. Unlike Scanner, BufferedReader does not automatically split input into tokens or convert numbers.
Choosing BufferedReader or Scanner
| Need | Better choice |
|---|---|
| Read complete lines and parse them yourself | `BufferedReader` |
| Read integers, words, and decimals directly | `Scanner` |
| Process a large amount of text efficiently | `BufferedReader` |
With BufferedReader, you control conversion and validation. That can make the input format explicit, but it also means you must handle NumberFormatException and blank lines yourself.
Unlike the mixed nextInt() and nextLine() problem in Scanner, BufferedReader has only one line-reading operation. Each call consumes the entire line, including its line ending. This makes line-oriented input predictable.
Resource ownership
The try-with-resources statement closes the BufferedReader automatically. Closing the reader also closes its underlying InputStreamReader and System.in.
Do not close a reader around System.in if another part of the program still needs to read from standard input. Usually, one component should own and close the input stream.
Exercise
What does BufferedReader.readLine() return when no more input is available?
Show answer
It returns null. A loop can continue while readLine() returns a non-null value.