Sunday, May 13, 2012

Difference between Scanner vs. BufferedReader

BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.


Where Scanner is a simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.


Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing. In currently latest JDK6 release/build, the Scanner has a littler buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer), but it's more than enough.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.


A BufferedReader is a simple class meant to efficiently read from the underling stream. Generally, each read request made of a Reader like a FileReadercauses a corresponding read request to be made to underlying stream. Each invocation of read() or readLine() could cause bytes to be readfrom 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 BufferedReadercan 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 parsethe 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 disregardingthe delimiter!  A scanner however is not thread safe, it has to be externally synchronized.

The choice of using a BufferedReader or a Scanner depends on the codeyou are writing, if you are writing a simple log reader Buffered readeris adequate. However if you are writing an XML parser Scanner isthe more natural choice.

2 comments em “Difference between Scanner vs. BufferedReader”

  • June 27, 2012
    aditya Disse:

    THanks a Lot this is valuable information....

    delete
  • June 27, 2012
    aditya Disse:

    THanks a Lot this is valuable information....

    delete

Post a Comment

Give your valuable Comment...

 

Programming, Data Structures & Algorithms Copyright © 2011 -- Template created by JAK -- Powered by Blogger