Can someone explain to me why can I use FileInputStream or FileReader for a BufferedReader? What's the difference? And at the same time what is the advantage of a Scanner over a BufferedReader? I was reading that it helps by tokenizing, but what does that mean?
FileReader is used to read a file from a disk drive whereas BufferedReader is not bound to only reading files. It can be used to read data from any character stream.
So, use FileReader if you intend to read streams of character and use the FileInputSream if you want to read streams of raw bytes. It's better to use FileReader for reading text files because it will take care of converting bytes to characters but remember that FileReader uses the platform's default character encoding.
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.
BufferedReader is a bit faster as compared to scanner because scanner does parsing of input data and BufferedReader simply reads sequence of characters.
Dexter's answer is already useful, but some extra explanation might still help:
In genereal: An InputStream only provides access to byte data from a source. A Reader can be wrapped around a stream and adds proper text encoding, so you can now read chars. A BufferedReader can be wrapped around a Reader to buffer operations, so instead of 1 byte per call, it reads a bunch at once, thereby reducing system calls and improving performance in most cases.
For files:
A FileInputStream is the most basic way to read data from files. If you do not want to handle text encoding on your own, you can wrap it into a InputStreamReader, which can be wrapped into a BufferedReader. Alternatively, you can use a FilerReader, which should basically do the same thing as FileInputStream + InputStreamReader.
Now if you do not want to just read arbitrary text, but specific data types (int, long, double,...) or regular expressions, Scanner is quite useful. But as mentioned, it will add some overhead for building those expressions, so only use it when needed.
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