4

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?

0

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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 and BufferedReader is synchronized and Scanner is not, so its up to you to decide.

EDIT System.in is a stream.

Comments

2

The main practical difference was simply that Scanner wasn't introduced until 1.5, and thus before that you had no choice but to to wrap System.in round various readers and then parse the output yourself to retrieve what you wanted.

Scanner manages a lot of this now for you, so unless you have a compelling reason to use BufferedReader and parse / process things entirely by yourself, I'd generally default to using Scanner - if nothing else because it makes the code clearer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.