Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking Input from the User

Tags:

java

io

What is the difference between taking input from Scanner and BufferedReader ?

Here is a BufferedReader example...

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");

// read characters
do {
    c = (char) br.read();
    System.out.println(c);
} while(c != 'q');

And here is a Scanner example...

Scanner scan = new Scanner(System.in);
char mrArray = new char[10];
// read characters
for (int i = 0; i < myArray.length; i++) {
    String temp = myScanner.next();
    myArray[i] = temp.charAt(0);
}

Is there any difference between the two cases? Are any of these classes likely to be changed in the future? Should I use BufferedStream in preference to Scanner?

like image 987
Arush Kamboj Avatar asked Dec 17 '22 01:12

Arush Kamboj


1 Answers

A BufferedReader is a simple class meant to efficiently read from the underling stream. Generally, each read request made of a Reader like a FileReader causes a corresponding read request to be made to underlying stream. Each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Efficiency is improved appreciably if a Reader is warped in a BufferedReader.
BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads.

A scanner on the other hand has a lot more cheese built into it; it can do all that a BufferedReader can do and at the same level of efficiency as well. However, in addition a Scanner can parse the underlying stream for primitive types and strings using regular expressions. It can also tokenize the underlying stream with the delimiter of your choice. It can also do forward scanning of the underlying stream disregarding the delimiter! A scanner however is not thread safe, it has to be externally synchronized.

Source : Scanner vs buffer reader

like image 125
Erwald Avatar answered Dec 18 '22 13:12

Erwald