5 Difference between BufferedReader and Scanner class in Java - Example

Even though both BufferedReader and Scanner can read a file or user input from command prompt in Java, there some significant differences between them. One of the main difference between BufferedReader and Scanner class is that former is meant to just read String while later is meant to both read and parse text data into Java primitive type e.g. int, short, float, double, and long. In other words, BufferedRedaer can only read String but Scanner can read both String and other data types like int, float, long, double, float etc. This functional difference drives several other differences on their usage. Another difference is Scanner is newer than BufferedReader, only introduced in Java 5, while BufferedReader is present in Java from JDK 1.1 version. This means, you have access to BufferedReader in almost all JDK version mainly Java 1.4 but Scanner is only available after Java 5.  This is also a popular core Java questions from interviews. Since many developer lack Java IO skill, questions like this test their knowledge about API and how to do some practical task.


You will not only learn about those key differences about BufferedReader and Scanner in this article but also about how to use them in Java program. You can also read Core Java Volume 2 - Advanced Features by Cay S. Horstmann to learn more about Java IO fundamentals. It's one of the key area in core Java programming which separate an intermediate Java developer to an expert one.

5 Difference between BufferedReader and Scanner class in Java


BufferedReader vs Scanner in Java

Here is the 5 key differences between the Scanner and BufferedReader class of Java API:

1. Scanner is a much more powerful utility than BufferedReader. It can parse the user input and read int, short, byte, float, long and double apart from String. On the other hand BufferedReader can only read String in Java.

2. BuffredReader has significantly large buffer (8KB) than Scanner (1KB), which means if you are reading long String from file, you should use BufferedReader but for short input and input other than String, you can use Scanner class.

3. BufferedReader is older than Scanner. It's present in Java from JDK 1.1 onward but Scanner is only introduced in JDK 1.5 release.

4. Scanner uses regular expression to read and parse text input. It can accept custom delimiter and parse text into primitive data type e.g. int, long, short, float or double using nextInt(), nextLong(), nextShort(), nextFloat(), and nextDouble() methods, while BufferedReader  can only read and store String using readLine() method.

5. Another major difference between BufferedReader and Scanner class is that BufferedReader is synchronized while Scanner is not. This means, you cannot share Scanner between multiple threads but you can share the BufferedReader object.

This synchronization also makes BufferedReader little bit slower in single thread environment as compared to Scanner, but the speed difference is compensated by Scanner's use of regex, which eventually makes BufferedReader faster for reading String.




Scanner and BufferedReader Example in Java

Though both BufferedReader and Scaner can be used to read a file, Scanner is usually used to read user input and BufferedReader is commonly used to read a file line by line in Java. One reason of this is Scanner's ability to read String, int, float or any other data type and BufferedReader's larger buffer size which can hold big lines from file in memory. Though it's not a restriction and you can even read a file using Scanner in Java. Alternatively, you can even read a file in just one line of code in Java 8.


Java Program to use Scanner and BufferedReader
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * Java Program to demonstrate how to use Scanner and BufferedReader class in
 * Java.
 *
 * @author WINDOWS 8
 *
 */
public class ScannerVsBufferedReader{

    public static void main(String[] args) {

        // Using Scanner to read user input
        Scanner scnr = new Scanner(System.in);
        System.out.println("=======================================");
        System.out.println("You can use Scanner to read user input");
        System.out.println("=======================================");
        System.out.println("Please enter a String");
        String name = scnr.nextLine();
        System.out.println("You have entered " + name);
        System.out.println("Please enter an integer");
        int age = scnr.nextInt();
        System.out.println("You have entered " + age);

        scnr.close();

        // Using BufferedReader to read a file
        System.out.println("=======================================");
        System.out.println("You can use BufferedReader to read a file");
        System.out.println("=======================================");
        FileReader fileReader;
        try {
            fileReader = new FileReader("abc.txt");
            BufferedReader buffReader = new BufferedReader(fileReader);

            System.out.println("File contains following lines");
            String line = buffReader.readLine();

            while (line != null) {
                System.out.println(line);
                line = buffReader.readLine();
            }

            buffReader.close();
            fileReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output
=======================================
You can use Scanner to read user input
=======================================
Please enter a String
James
You have entered James
Please enter an integer
32
You have entered 32
=======================================
You can use BufferedReader to read a file
=======================================
File contains following lines
1. Which is best SmartPhone in the market?
a) iPhone 6S
b) Samsung Galaxy Edge
c) Something else

You can see that Scanner is capable of reading both String and numeric data from command line. You can also see how easy it is to read a file line by line using BufferedReader.

Here is a summary of all the differences between Scanner and BufferedReader in Java:

Scanner vs BufferedReader in Java


That's all about difference between Scanner and BufferedReader class in Java. Even though, both are capable of reading user input from console, you should use Scanner if input is not big and you also want to read different types of input e.g. int, float and String. Use BufferedReader is you want to read text without parsing. Since it has larger buffer, you can also use to read long String in Java.

Further Reading
2 ways to read a text file in Java? (solution)
How to read an Excel file in Java? (solution)
How to read a CSV file in Java? (example)
How to create a file and directory in Java? (answer)
How to read an XML file in Java? (answer)
How to append text to an existing file in Java? (example)
Core Java for Really Impatient (see here)


No comments:

Post a Comment