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?

- 4,532
- 4
- 53
- 64

- 177
- 1
- 5
- 14
-
1If you have to read a file you can use apache commons io: `String string = FileUtils.readFileToString(file);` so that you donot have to worry about readers. – thiyaga Dec 30 '13 at 11:21
2 Answers
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 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);

- 1,421,763
- 867
- 9,128
- 9,194
-
-
1
-
@MarkoTopolnik: Thanks, hadn't seen that. Will add it into the answer. – Jon Skeet Dec 30 '13 at 11:26
-
Is it `readLines` have facility to fetch desired number of rows or just stop after `n` lines, I think it will also load all the lines to memory so it will be problem for big files.... – Deepak Bhatia Dec 30 '13 at 11:32
-
@dbw: If you only want to process some lines, there are alternatives in Guava such as the `CharStreams.readLines(InputSupplier, LineProcessor)` method. – Jon Skeet Dec 30 '13 at 11:39
-
great anwer but will you explain me thus "Personally I find the API of Scanner to be pretty painful and obscure." I mean why? – Govinda Sakhare Feb 29 '16 at 06:12
-
@piechuckerr: The fact that there are so many questions with it being used badly is pretty damning. It defies the expectations of users in many cases. My experience is that it's hard to use robustly and correctly. – Jon Skeet Feb 29 '16 at 06:48
And as per your question for reading a text file you should use BufferedReader
because Scanner
hides IOException while BufferedReader
throws it immediately.
BufferedReader
is synchronized and Scanner
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)

- 4,532
- 4
- 53
- 64

- 489
- 5
- 20
-
1Thank you for your answer. I don't see a reason why read operation needs to be synchronized. Do you understand the reasoning behind this design decision ? – Aazim Apr 29 '18 at 20:00