tags:

views:

191

answers:

3

As far I know, the two most common methods of reading character-based data from a file in Java is using Scanner or BufferedReader. I also know that the BufferedReader read files efficiently by using a buffer to avoid physical disk operations. My questions are:

  • Does Scanner performs as well as BufferedReader?
  • Why would you choose Scanner over BufferedReader or vica versa?
+10  A: 

Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.

In fact you can pass a BufferedReader to a scanner as the source of characters to parse.

Chandru
+3  A: 

In currently latest JDK6 release/build, the Scanner has a littler buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer), but it's more than enough.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

BalusC
A: 
  1. BufferedReader will probably give you better performance (because Scanner is based on InputStreamReader, look sources). ups, for reading from files it uses nio. When I tested nio performance against BufferedReader performance for big files nio shows a bit better performance.
  2. For reading from file try Apache Commons IO.
Roman