Difference between Scanner and BufferReader in java

In this post, we will see difference between Scanner and BufferReader in java.

Java has two classes that have been used for reading files for a very long time.
These two classes are Scanner and BufferedReader.

In this post, we are going to find major differences and similarities between the two classes.

Introduction

Let’s first go through quick introduction to Scanner and BufferReader classes.

Scanner

Scanner class can be used for user input by importing from java.util package.
A user can read numbers from System.in(From your command line) by using Scanner class.

Let’s try a simple example to understand the working of the Scanner class.

The output of the above program will be:

If you don’t want to read from terminal only and want to read from a given file in that case, Scanner class can be used.

BufferedReader

BufferedReader class can be used by importing from java.io package. It reads characters from any input stream line. If you want to read from a file by using BufferedReader, you need to use an appropriate file reader. It can use readLine() to read data line by line.

BufferedReader br = new BufferedReader(new FileReader(“fileName”));

BufferedReader buffers characters and uses it in efficient readings of characters, arrays, lines, etc.

Let’s understand the functioning of BufferedReader by an example

Output of the above code will be

Difference between Scanner and BufferedReader

  1. If you have a small application where you don’t care much about synchronization and concurrency, you can use the Scanner class whereas in a thread-safe environment BufferedReader will be a good choice.
  2. Scanner class has a smaller buffer memory of 1024 chars, whereas BufferedReader has a default buffer memory of 8192 chars, and that too can be extended.
  3. Scanner class comes from JDK 1.5, so old applications that support JDK 1.5 can not use Scanner class. BufferedReader class is with java from JDK 1.1, so it supports applications that use older versions of java.
  4. Scanner class uses regular expression in parsing the strings, by default, white space gets set as a delimiter, but you can set any other delimiter.
  5. BufferedReader is only used for reading data, whereas Scanner class is used for reading as well as parsing of data.

That’s all about difference between Scanner and BufferReader in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *