Difference between buffered reader and file reader and scanner class

Charbel picture Charbel · Dec 30, 2013 · Viewed 28.5k times · Source

Can anyone explain me the difference between the class BufferedReader, FileReader and Scanner? and which one to use when I want to read a text file?

Answer

Jon Skeet picture Jon Skeet · Dec 30, 2013

Well:

  • FileReader is just a Reader which reads a file, using the platform-default encoding (urgh)
  • BufferedReader is a wrapper around another Reader, adding buffering and the ability to read a line at a time
  • Scanner reads from a variety of different sources, but is typically used for interactive input. Personally I find the API of Scanner to be pretty painful and obscure.

To read a text file, I would suggest using a FileInputStream wrapped in an InputStreamReader (so you can specify the encoding) and then wrapped in a BufferedReader for buffering and the ability to read a line at a time.

Alternatively, you could use a third-party library which makes it simpler, such as Guava:

File file = new File("foo.txt");
List<String> lines = Files.readLines(file, Charsets.UTF_8);

Or if you're using Java 7, it's already available for you in java.nio.file.Files:

Path path = FileSystems.getDefault().getPath("foo.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);