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
In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.
As to the choice, use the Scanner
if you want to parse the file, use the BufferedReader
if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.
nextXxx()
methods in Scanner
class. Following are the differences between BufferedReader and Scanner
Thanks
There are different ways of taking input in java like:
1) BufferedReader 2) Scanner 3) Command Line Arguments
BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
Where Scanner is a simple text scanner which can parse primitive types and strings using regular expressions.
if you are writing a simple log reader Buffered reader is adequate. if you are writing an XML parser Scanner is the more natural choice.
For more information please refer:
http://java.meritcampus.com/t/240/Bufferedreader?tc=mm69
I suggest to use BufferedReader
for reading text. Scanner
hides IOException
while BufferedReader
throws it immediately.
Difference between BufferedReader and Scanner are following:
Code to read a line from console:
BufferedReader:
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
String st= br.readLine();
Scanner:
Scanner sc= new Scanner(System.in);
String st= sc.nextLine();
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 using BufferedReader
. 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.