Scanner versus BufferedReader
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Scanner reads input as tokens (words and numbers) and converts them for you; BufferedReader reads whole lines that you split and convert yourself. Scanner is easier for small input, BufferedReader is much faster for big input.
Scanner on a Path with a charset
A token is one piece of input between spaces or line breaks, such as Asha or 86. new Scanner(path, StandardCharsets.UTF_8) (Java 10 and later) reads a file token by token: next() gives a word, nextInt() a whole number, nextLine() the rest of the current line.
Example 1 · Scanner on a file with a charset
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.Scanner;
public class ScannerFileDemo { public static void main(String[] args) throws IOException { Path file = Path.of("scores.txt"); Files.writeString(file, "Asha 86 92\nRavi 72 65\n");
try (Scanner sc = new Scanner(file, StandardCharsets.UTF_8)) { while (sc.hasNext()) { String name = sc.next(); int theory = sc.nextInt(); int lab = sc.nextInt(); System.out.println(name + " total " + (theory + lab)); } }
Files.delete(file); }}Asha total 178 Ravi total 137
What this code does
next()reads a word andnextInt()reads a whole number. Spaces and line breaks between them are skipped, so the extra spaces on Ravi's line do not matter.ScannerisAutoCloseable, so try-with-resources closes the file at the end.
Without the charset, a Scanner on a file uses the default charset, which was windows-1252 on English Windows before Java 18. So pass StandardCharsets.UTF_8, and open the Scanner in try-with-resources.
IOException while reading. On a read error it simply stops, and sc.ioException() tells you what went wrong.Token reading with nextInt and its traps
nextInt() reads the next token as an int. Two traps catch almost everyone. First, it stops right before the line break, so a nextLine() straight after it returns an empty String. Second, if the token is not a number, such as absent, it throws InputMismatchException.
Example 2 · Trap: nextLine right after nextInt
import java.util.Scanner;
public class NextLineTrapDemo { public static void main(String[] args) { // Same text a user would type: a count, then one full name per line Scanner sc = new Scanner("2\nAsha Rao\nRavi Kumar\n");
int count = sc.nextInt(); String first = sc.nextLine(); String second = sc.nextLine();
System.out.println("count = " + count); System.out.println("first = [" + first + "]"); System.out.println("second = [" + second + "]"); }}count = 2 first = [] second = [Asha Rao]
What this code does
nextInt()reads2and stops right before the line break. The firstnextLine()then reads the rest of that line, which is empty.- Every name is now one step late, and the last one is never read. The brackets make the empty String visible.
Example 3 · The fixes: skip the rest of the line, or check with hasNextInt
import java.util.Scanner;
public class NextLineFixDemo { public static void main(String[] args) { Scanner sc = new Scanner("2\nAsha Rao\nRavi Kumar\n"); int count = sc.nextInt(); sc.nextLine(); // finish the line that held the count for (int i = 1; i <= count; i++) { System.out.println("Name " + i + ": " + sc.nextLine()); }
Scanner marks = new Scanner("86 absent 72 91"); int total = 0; while (marks.hasNext()) { if (marks.hasNextInt()) { total += marks.nextInt(); } else { System.out.println("Skipped: " + marks.next()); } } System.out.println("Total: " + total); }}Name 1: Asha Rao Name 2: Ravi Kumar Skipped: absent Total: 249
What this code does
- One extra
nextLine()afternextInt()throws away the rest of the count's line. Another fix is to read every line withnextLine()and convert withInteger.parseInt(line.trim()). nextInt()onabsentwould throwInputMismatchException.hasNextInt()looks ahead without reading, so the program can skip the word instead.
The fixes: call one extra nextLine() after nextInt(), or read whole lines and parse them with Integer.parseInt(line.trim()). Use hasNextInt() to check before reading when the input may contain words.
Speed difference on big input
Scanner is slow on big input because it uses pattern matching (regular expressions) to find and check every token. For a few hundred values you will never notice. For a million numbers it is often several times slower than the alternative.
Example 4 · Speed test: one million numbers
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.Scanner;import java.util.StringTokenizer;
public class InputSpeedDemo { public static void main(String[] args) throws IOException { Path file = Path.of("numbers.txt"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1_000_000; i++) { sb.append((i * 37) % 1000).append(i % 10 == 9 ? "\n" : " "); } Files.writeString(file, sb.toString());
long start = System.nanoTime(); long scannerSum = 0; try (Scanner sc = new Scanner(file, StandardCharsets.UTF_8)) { while (sc.hasNextInt()) { scannerSum += sc.nextInt(); } } long scannerMs = (System.nanoTime() - start) / 1_000_000;
start = System.nanoTime(); long readerSum = 0; try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { String line; while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { readerSum += Integer.parseInt(st.nextToken()); } } } long readerMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("Scanner: sum " + scannerSum + " in " + scannerMs + " ms"); System.out.println("BufferedReader: sum " + readerSum + " in " + readerMs + " ms"); Files.delete(file); }}Scanner: sum 499500000 in 487 ms BufferedReader: sum 499500000 in 64 ms
What this code does
System.nanoTime()reads a precise clock; the difference between two readings, divided by 1,000,000, is the time in milliseconds. Your times will differ, but the gap is usually several times.StringTokenizer(injava.util) splits a line into words on spaces and tabs. WithInteger.parseIntit does the same job asnextInt, without the pattern matching Scanner does for every token.
The fast way is a BufferedReader that reads lines, a StringTokenizer that splits each line into tokens on spaces, and Integer.parseInt for the numbers. StringTokenizer is an old class from java.util, but simple and fast for space-separated input.
Fast input reading for coding rounds
In coding rounds with large inputs and a time limit, use a BufferedReader on System.in, a StringTokenizer per line, and a StringBuilder for all output, printed once at the end.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));int n = Integer.parseInt(in.readLine().trim());StringTokenizer st = new StringTokenizer(in.readLine());StringBuilder out = new StringBuilder();for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); out.append(x * 2).append('\n');}System.out.print(out);Example 5 · Fast input for a coding-round problem
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.StringTokenizer;
public class FastInputDemo { // Reads: n, then n numbers. Prints the sum and the largest number. static String solve(BufferedReader in) throws IOException { int n = Integer.parseInt(in.readLine().trim()); StringTokenizer st = new StringTokenizer(in.readLine()); long sum = 0; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); sum += x; max = Math.max(max, x); } StringBuilder out = new StringBuilder(); out.append("sum ").append(sum).append('\n'); out.append("max ").append(max).append('\n'); return out.toString(); }
public static void main(String[] args) throws IOException { Path input = Path.of("input.txt"); // stands in for the judge's input Files.writeString(input, "5\n3 9 -2 7 4\n"); try (BufferedReader in = Files.newBufferedReader(input)) { System.out.print(solve(in)); } Files.delete(input); }}sum 21 max 9
What this code does
solveonly needs aBufferedReader. Here it comes from a file so you can run it anywhere; in a real coding round you pass the reader built onSystem.infrom the snippet above.- All output is collected in a
StringBuilderand printed once. With 2 lakh lines of output, one bigprintis much faster than 2 lakhprintlncalls.
InputStreamReader turns the bytes of System.in into characters; the Byte & Character Streams module explains it. Put the logic in a method that takes a BufferedReader, so you can test it with a file, as in the next example. Use long for sums that can pass about 2.1 × 10⁹.
Next step
Check your understanding
10 quick questions