Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner vs. BufferedReader

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 reads files efficiently by using a buffer to avoid physical disk operations.

My questions are:

  • Does Scanner perform as well as BufferedReader?
  • Why would you choose Scanner over BufferedReader or vice versa?
like image 337
Mads Mobæk Avatar asked Feb 09 '10 18:02

Mads Mobæk


People also ask

Can I use Scanner and BufferedReader in Java?

You can only read String using BufferedReader, using Scanner you can read to different data types like int . BufferedReader is older than Scanner, it was added on JDK 1.1 , while Scanner was added on JDK 5 release. The buffer size of BufferedReader is larger (8KB) as compared to Scanner's 1KB.

What is the difference between Scanner and FileReader?

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.

Why BufferedReader is faster than FileReader?

Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory. Each time you want to read the file data, you can read it from the buffer( you don't have to directly access the disk drive every time) and hence is faster than FileReader.


1 Answers

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.

like image 181
Chandra Sekar Avatar answered Sep 30 '22 15:09

Chandra Sekar