Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader vs Scanner, and FileInputStream vs FileReader?

Tags:

java

android

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?

like image 737
OHHH Avatar asked Nov 26 '14 19:11

OHHH


People also ask

What is the difference between FileReader and BufferedReader?

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.

Should I use FileReader or FileInputStream?

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.

What is the difference between FileReader and Scanner?

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.

Is it better to use Scanner or BufferedReader?

BufferedReader is a bit faster as compared to scanner because scanner does parsing of input data and BufferedReader simply reads sequence of characters.


1 Answers

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.

like image 198
Silverclaw Avatar answered Oct 18 '22 21:10

Silverclaw