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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With