So, should we use Scanner or BufferedReader? Well, if we need to parse the file, then Scanner is the way to go; otherwise, BufferedReader is more suitable. A head-to-head comparison of them will reveal the following:
- BufferedReader is faster than Scanner since it doesn't perform any parsing operations.
- BufferedReader excels when it comes to reading while Scanner excels when it comes to parsing.
- By default, BufferedReader uses a buffer of 8 KB, while Scanner uses a buffer of 1 KB.
- BufferedReader is a good fit for reading long strings, while Scanner is better for short inputs.
- BufferedReader is synchronized, but Scanner is not.
- A Scanner can use a BufferedReader, while the opposite is not possible. This is shown in the following code:
try (Scanner scanDoubles = new Scanner(Files.newBufferedReader(
Path.of("doubles.txt"), StandardCharsets.UTF_8))) {
...
}