This question already has an answer here:
- Scanner vs. BufferedReader 12 answers
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?
This question already has an answer here:
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?
Well:
FileReader
is just aReader
which reads a file, using the platform-default encoding (urgh)BufferedReader
is a wrapper around anotherReader
, adding buffering and the ability to read a line at a timeScanner
reads from a variety of different sources, but is typically used for interactive input. Personally I find the API ofScanner
to be pretty painful and obscure.To read a text file, I would suggest using a
FileInputStream
wrapped in anInputStreamReader
(so you can specify the encoding) and then wrapped in aBufferedReader
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:
Or if you're using Java 7, it's already available for you in
java.nio.file.Files
:And as per your question for reading a text file you should use
BufferedReader
becauseScanner
hides IOException whileBufferedReader
throws it immediately.BufferedReader
is synchronized andScanner
is not.Scanner
is used for parsing tokens from the contents of the stream.BufferedReader
just reads the stream.For more info follow the link (http://en.allexperts.com/q/Java-1046/2009/2/Difference-Scanner-Method-Buffered.htm)