Difference Between Scanner and BufferReader Class in Java
Difference Between Scanner and BufferReader Class in Java
in Java
java.util.Scanner class is a simple text scanner which can parse primitive types and strings. It internally uses
regular expressions to read different types. Java.io.BufferedReader class reads text from a character-input
stream, buffering characters so as to provide for the efficient reading of sequence of characters Following are
differences between above two.
filter_none
edit
play_arrow
brightness_4
Input:
50
Geek
Output:
Enter an integer
Enter a String
You have entered:- 50 and name as
Let us try the same using Buffer class and same Input
filter_none
edit
play_arrow
brightness_4
Input:
50
Geek
Output:
Enter an integer
Enter a String
you have entered:- 50 and name as Geek
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine()
doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX()
methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for Scanner class, due to
nextXXX() methods ignore newline character and nextLine() only reads till first newline character. If we use
one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur
because nextLine() will consume the newline character. See this for the corrected program. This problem is
same as scanf() followed by gets() in C/C++.
Other differences:
BufferedReader is synchronous while Scanner is not. BufferedReader should be used if we are working
with multiple threads.
BufferedReader has significantly larger buffer memory than Scanner.
The Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer),
but it’s more than enough.
BufferedReader is a bit faster as compared to scanner because scanner does parsing of input data and
BufferedReader simply reads sequence of characters.
Java.io.InputStream & InputStreamReader Class
in Java
InputStream class is the superclass of all the io classes i.e. representing an input stream of bytes. It represents
input stream of bytes. Applications that are defining subclass of InputStream must provide method, returning
the next byte of input.
A reset() method is invoked which re-positions the stream to the recently marked position.
package com.zetcode;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
os.flush();