Video in progress

Why do we need BufferedReader? Isn't a plain FileReader enough?

FileReader has a small byte buffer inside, but every read() is a separate expensive call, and it has no readLine(). BufferedReader pulls characters into memory in big chunks (8192 characters by default) and gives you the handy readLine() method.

📖 Answer

FileReader is really an InputStreamReader: it reads bytes from the file in chunks, but each read() call is a synchronized method plus decoder work. If you read characters one at a time, this is noticeably slow. With a plain FileInputStream.read(), every byte really is a separate system call, so the buffer matters even more there.

try (BufferedReader br = Files.newBufferedReader(Path.of("users.csv"))) {
    String line;
    while ((line = br.readLine()) != null) {
        // process each line
    }
}

readLine() strips the \n or \r\n at the end of the line and returns null when the file ends.

In practice Files.newBufferedReader(path) is nicer than new BufferedReader(new FileReader(...)): it uses UTF-8 by default and makes the code shorter.

The same goes for writing: BufferedWriter or Files.newBufferedWriter.