Sub topic 12
BufferedReader as an alternative
This chapter assumes you have read the earlier chapters on Scanner, the leftover newline pitfall, and end of input. It also assumes you know checked exceptions and try-with-resources. Here you will read console input with java.io.BufferedReader, the standard library's older, lower-level option. You will see what it gives you, what it makes you do yourself, and when it is the better choice.
Why consider it
Scanner parses text for you. It splits input into tokens, converts them to int or double, and uses regular expressions to do so. That convenience has a cost. Scanner is slower than plain line reading, and its behavior around newlines and delimiters surprises people.
BufferedReader does one job: it reads characters from a source and hands you whole lines. It does not parse numbers or split tokens. You write that code yourself, using methods you already know such as Integer.parseInt and String.split. In return you get:
- Predictable behavior. There is only one reading method for text,
readLine, so the leftover newline pitfall cannot happen. - Speed.
BufferedReaderis noticeably faster thanScannerwhen a program reads many thousands of lines, as in programming contests or log processing. - A familiar API. The same class reads files, sockets, and standard input.
Building the reader
System.in is an InputStream, which delivers bytes. BufferedReader needs a Reader, which delivers characters. InputStreamReader is the bridge that decodes bytes into characters. BufferedReader then adds a buffer, so it reads input in large chunks and serves lines from memory.
The usual construction is one line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));The one-argument InputStreamReader constructor decodes with the platform's default charset. If you know the input encoding, pass it explicitly so the program behaves the same on every machine:
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in, StandardCharsets.UTF_8));This matters only for non-ASCII text such as accented letters. Plain digits and English words decode the same under almost every charset.
Reading lines until the input ends
readLine returns the next line without its line terminator. It recognizes \n, \r, and \r\n. At the end of input it returns null. That return value is how you detect the end, instead of calling hasNextLine as you did with Scanner.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LineCounter {
public static void main(String[] args) throws IOException {
int lines = 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
while (reader.readLine() != null) {
lines++;
}
}
System.out.println("Lines: " + lines);
}
}Run it with input piped from a file (java LineCounter < notes.txt) or type lines at the keyboard and end the input yourself. End input with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows.
Three details are worth noting:
readLinethrowsIOException, a checked exception. Either declare it withthrows, as above, or catch it.Scannerhides I/O errors instead, and you would have to callioException()to see them.- An empty line comes back as an empty string
"", notnull. Only the end of input producesnull. - If the last line has no terminator,
readLinestill returns it. The next call then returnsnull.
Parsing numbers yourself
Because readLine returns a String, conversion is your job. The method to use is Integer.parseInt, and it throws NumberFormatException for text that is not a valid integer. Leading or trailing spaces also make it fail, so call trim first.
This program sums one number per line. It skips blank lines and reports bad ones instead of crashing.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class SumLines {
public static void main(String[] args) throws IOException {
long sum = 0;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
try {
sum += Long.parseLong(line);
} catch (NumberFormatException e) {
System.err.println("Skipping: " + line);
}
}
}
System.out.println("Sum: " + sum);
}
}The loop condition (line = reader.readLine()) != null assigns and tests in one step. It is the standard idiom for reading until the end.
Compare the validation strategy with Scanner. There you asked hasNextInt before reading. Here you attempt the conversion and catch the failure. Both are valid. With BufferedReader the bad line has already been consumed when you find the problem, so you never need to discard it.
Several values on one line
Scanner splits tokens for you. With BufferedReader you split the line. Suppose the first line holds a count n and the second line holds n integers separated by spaces:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MaxOfN {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine().trim());
String[] parts = reader.readLine().trim().split("\\s+");
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
max = Math.max(max, Integer.parseInt(parts[i]));
}
System.out.println("Max: " + max);
}
}split("\\s+") splits on runs of whitespace. Calling trim first avoids an empty leading element, because splitting " 3 4" produces ["", "3", "4"]. This program has no error handling, so it fails with a NullPointerException if the input ends early, and with NumberFormatException or ArrayIndexOutOfBoundsException on malformed input. In real code, check for null from each readLine before using it.
java.util.StringTokenizer is an older alternative to split. It is a little faster, but it is a legacy class. Prefer split unless you have measured a need.
Reading everything as a stream
Since Java 8, BufferedReader.lines() returns a Stream<String> of the remaining lines. It suits whole-input processing:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StreamSum {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
long sum = reader.lines()
.map(String::trim)
.filter(s -> !s.isEmpty())
.mapToLong(Long::parseLong)
.sum();
System.out.println("Sum: " + sum);
}
}There is no throws IOException here. If an I/O error occurs while streaming, the stream wraps it in an unchecked UncheckedIOException. A bad number still throws NumberFormatException from inside the pipeline and stops it, so this version is less forgiving than SumLines.
Edge cases and pitfalls
Closing also closes System.in
As with Scanner, closing the BufferedReader closes the InputStreamReader and then System.in. After that, no part of the program can read standard input again. If the reader is the only consumer, try-with-resources is correct. If you create readers inside a helper method that is called many times, create one reader and pass it around, or do not close it.
Do not mix readers on one System.in
A BufferedReader reads ahead. When it asks the operating system for data, it may take several lines at once and hold the extra ones in its buffer. If you then create a Scanner on System.in, those buffered lines are gone from the stream, and the Scanner never sees them. The same happens with two BufferedReader objects. Pick one reader for the life of the program.
Blocking and prompts
readLine blocks until a full line arrives or the input ends. Nothing is returned for a partial line. Print your prompt with System.out.print before calling it, as you did with Scanner. If the prompt does not appear before you type, call System.out.flush() after printing.
Character encoding
If accented or non-Latin characters arrive as ? or garbled symbols, the decoding charset does not match the terminal. Passing the correct charset to InputStreamReader is the fix. Check what your terminal actually sends, because a UTF-8 constant is wrong on a console set to another encoding.
No password support
BufferedReader echoes what you type. For secrets, use Console.readPassword as covered in the Console chapter.
Scanner compared with BufferedReader
| Concern | Scanner | BufferedReader |
|---|---|---|
| Reads whole lines | `nextLine` | `readLine` |
| Reads numbers directly | `nextInt`, `nextDouble` | No, parse with `Integer.parseInt` |
| Signals end of input | `hasNext...` methods, `NoSuchElementException` | `readLine` returns `null` |
| Checked exceptions | None | `IOException` |
| Leftover newline pitfall | Yes, when mixing token and line reads | No |
| Speed on large input | Slower | Faster |
| Custom delimiters | `useDelimiter` | Write it with `split` |
Choose BufferedReader when input is line-oriented, large, or already in a simple format. Choose Scanner when you want quick token parsing and the input is small, such as a classroom exercise or an interactive prompt.
Exercises
Exercise
A program reads lines with while ((line = reader.readLine()) != null). The user types an empty line and presses Enter. Does the loop stop? Why or why not?
Show answer
No. An empty line is returned as the empty string "", which is not null, so the loop body runs. Only the end of input makes readLine return null.
Exercise
Write a method static int readIntLine(BufferedReader reader) throws IOException that reads one line and returns it as an int. It should throw an IllegalStateException with the message "Input ended" if the input has ended, and it should tolerate spaces around the number.
Show answer
static int readIntLine(BufferedReader reader) throws IOException { String line = reader.readLine(); if (line == null) { throw new IllegalStateException("Input ended"); } return Integer.parseInt(line.trim()); }
Exercise
A program creates a BufferedReader on System.in, reads one line, and then creates a Scanner on System.in to read the rest. The Scanner sometimes finds no input even though the user typed several lines. Explain the cause and give a fix.
Show answer
The BufferedReader reads ahead and stores extra data in its internal buffer, so those lines are no longer in System.in when the Scanner starts. Fix it by using one reader for the whole program. For example, use only the BufferedReader and split or parse each line yourself, or use only the Scanner.