• Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferedReader vs Scanner  RSS feed

 
Ryan Bishop
Ranch Hand
Posts: 143
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is there a big difference between BufferedReader and the Scanner class? Are there advantages/disadvantages using one instead of the other?
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I usually use BufferedReader if I need to read the entire input line by line.

If I'm looking for specific data in a file, I prefer to use Scanner, because it can search using regular expressions.

For instance, if your application reads a log or a book or something like that and displays (a part of) the contents, I would use BufferedReader.

If your application reads a configuration file and you need some named entries, I would use Scanner.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suspect Scanner uses a buffered reader behind the scenes and it consumes any Exceptions, so Scanner is easier to use. It breaks the input into separate tokens and does the parsing for you, but there are pitfalls with nextLine.
I use Scanner by preference. As Stefan says, you usually only read a line at a time with a buffered reader.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Bishop wrote:Is there a big difference between BufferedReader and the Scanner class? Are there advantages/disadvantages using one instead of the other?

As Campbell will tell you, I'm not a big fan of Scanner.

That said: why can't you use both? One nice thing about Scanners is that you can create them for Strings; and that means that you can use a BufferedReader to read your "lines" (or keyboard input until your user presses <ENTER>), and then use a Scanner to "break up" (or validate) the "lines" you receive.

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is something about Scanners which people often forget. You often use Scanner#hasNextInt for keyboard input, but you can also use it for Strings from any source.There is a bit more about "\\s*,\\s*" here.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!