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
reads files efficiently by using a buffer to avoid physical disk operations.
My questions are:
Scanner
perform as well as BufferedReader
?Scanner
over BufferedReader
or vice versa?You can only read String using BufferedReader, using Scanner you can read to different data types like int . BufferedReader is older than Scanner, it was added on JDK 1.1 , while Scanner was added on JDK 5 release. The buffer size of BufferedReader is larger (8KB) as compared to Scanner's 1KB.
Well: FileReader is just a Reader which reads a file, using the platform-default encoding (urgh) BufferedReader is a wrapper around another Reader , adding buffering and the ability to read a line at a time. Scanner reads from a variety of different sources, but is typically used for interactive input.
Whereas, BufferedReader creates a buffer, and reads large amount of data using the given FileReader and loads it into a input buffer in the memory. Each time you want to read the file data, you can read it from the buffer( you don't have to directly access the disk drive every time) and hence is faster than FileReader.
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 fact you can pass a BufferedReader
to a scanner
as the source of characters to parse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With