While Scanner is relatively slower, it is often more than fast enough, and it is much more powerful than BufferedReader.
public static void main(String... args) throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10000; i++) sb.append("line: ").append(i).append("\n"); String lines = sb.toString(); for (int i = 0; i < 6; i++) { testBufferedReader(lines); testScanner(lines); } } private static void testBufferedReader(String text) throws IOException { int count = 0; BufferedReader br = new BufferedReader(new StringReader(text)); long start = System.nanoTime(); while (br.readLine() != null) count++; long time = System.nanoTime() - start; System.out.printf("BufferedReader.readLine() took an average of %,d ns count=%,d%n", time / count, count); } private static void testScanner(String text) throws IOException { int count = 0; Scanner sc = new Scanner(new StringReader(text)); long start = System.nanoTime(); while (sc.hasNextLine()) { sc.nextLine(); count++; } long time = System.nanoTime() - start; System.out.printf("Scanner nextLine took an average of %,d ns count=%,d%n", time / count, count); }
finally prints
BufferedReader.readLine() took an average of 124 ns count=10,000 Scanner nextLine took an average of 1,549 ns count=10,000
While the relative difference is large, the scanner is smaller than a few microseconds each.
source share