What is the difference between Java's BufferedReader and InputStreamReader classes?
BufferedReader is a wrapper for both "InputStreamReader/FileReader", which buffers the information each time a native I/O is called.
You can imagine the efficiency difference with reading a character(or bytes) vis-a-vis reading a large no. of characters in one go(or bytes). With BufferedReader, if you wish to read single character, it will store the contents to fill its buffer (if it is empty) and for further requests, characters will directly be read from buffer, and hence achieves greater efficiency.
InputStreamReader converts byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
Hope it helps.
Reading from main memory is faster than reading from disk/STDIN.
BufferedReader
uses a technique called buffering that allows us to reduce how often we read from disk/STDIN by copying chunks to main memory.
Consider:
BufferedReader in = new InputStreamReader(System.in);
in.read(); //
in.read(); //
// ...
in.read(); // could be hitting the disk/STDIN a lot (slow!)
vs:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
in.read(); //
in.read(); //
// ...
in.read(); // hitting main memory a lot (fast!)
From the documentation:
Without buffering, each invocation of
read()
could cause bytes to be read from [disk/STDIN], converted into characters, and then returned, which can be very inefficient.
The two classes implement the same interface of Reader
. So while you could use just InputStreamReader
without BufferedReader
, it could result in poor performance. We are just using the decorator pattern here so that we end up with a InputStreamReader
which now has a buffering capability.
The InputStreamReader class adapts type InputStream (uninterpreted bytes) to the Reader class (bytes interpreted as characters in some character set), but does not apply any additional buffering. The BufferedReader class takes a Reader class (presumably unbuffered) and applies buffering to it.