As far I know, the two most common methods of reading character-based data from a file in Java is using Scanner
or BufferedReader
. I also know that the BufferedReader
read files efficiently by using a buffer to avoid physical disk operations. My questions are:
- Does
Scanner
performs as well asBufferedReader
? - Why would you choose
Scanner
overBufferedReader
or vice versa?
Scanner
is used for parsing tokens from the contents of the stream whileBufferedReader
just reads the stream and does not do any special parsing.In fact you can pass a
BufferedReader
to ascanner
as the source of characters to parse.The answer below is taken from Reading from Console: JAVA Scanner vs BufferedReader
When read an input from console, there are two options exists to achieve that. First using
Scanner
, another usingBufferedReader
. Both of them have different characteristics. It means differences how to use it.Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().
But, what is others differences between?
Scanner come with since JDK version 1.5 higher.
When should use Scanner, or Buffered Reader?
Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it’s use buffer when read a file. Or you can use BufferedReader as input to Scanner.
See this link, following is quoted from there:
BufferedReader
has significantly larger buffer memory than Scanner. UseBufferedReader
if you want to get long strings from a stream, and useScanner
if you want to parse specific type of token from a stream.Scanner
can use tokenize using custom delimiter and parse the stream into primitive types of data, whileBufferedReader
can only read and store String.BufferedReader
is synchronous whileScanner
is not. UseBufferedReader
if you're working with multiple threads.Scanner
hides IOException whileBufferedReader
throws it immediately.I suggest to use
BufferedReader
for reading text.Scanner
hidesIOException
whileBufferedReader
throws it immediately.Following are the differences between BufferedReader and Scanner
Thanks