问题
I need to understand the difference between these two classes and how they work with each other. I understand that FileReader reads characters from a file one character at a time and the BufferedReader reads a large chunk of data and stores it in a buffer and thus makes it faster.
In order to use a BufferedReader, i have to provide it a FileReader. How does the BufferedReader class use the FileReader if it reads the file differently? Does it mean that BufferedReader uses FileReader and therefore behind the scenes the characters are still read one character at a time? I guess my question is how does the BufferedReader class use the FileReader class.
回答1:
First of all, BufferedReader
takes a Reader
, not a FileReader
(although the latter is accepted).
The Reader
abstract class has several read()
methods. There is a read-one-character version as well as two versions that read a block of characters into an array.
It only makes sense to use BufferedReader
if you're reading single characters or small blocks at a time.
Consider the following two requests:
char ch1 = fileReader.read();
char ch2 = bufferedReader.read()
The first one will go to the underlying file, whereas the second one will most probably be satisfied from the BufferedReader
's internal buffer.
回答2:
The BufferedReader uses the FileReader.read(char[] cbuf, int off, int len)
method which you can also read if you want to get more than one character at a time.
The BufferedReader makes it simpler to read the size you want and still be efficient. If you are always reading large blocks, it can be slightly more efficient to drop the BufferedReader.
回答3:
A FileReader has the ability to read chunks, not just 1 character at a time. It inherits the read(char[]) methods from Reader
so you can read up to the size of the char[] array that you pass in. The BufferedReader simply wraps the FileReader so when you call the read() methods on BufferedReader, it handles buffers internally and calls the read() methods on its underlying Reader. One of the main reasons you'd use a BufferedReader is so you can use the readLine() method. A BufferedReader can wrap other Readers besides a FileReader (such as InputStreamReader).
回答4:
The BufferedReader adds a layer of buffering on top of any reader. The point is to make reading more optimal compared to reading a file, socket or something in an unbuffered way. It also adds a few convenient methods which wouldn't work very well unless it prefetched a chunk for you. In the FileReader case, you have to read a chunk of data until you find a '\n' to be able to do something like BufferedReader.readLine() and then you would have to keep the rest of the data for the next read operation (not to mention the work needed when you have to wait for a slow data source to deliver it all to you).
来源:https://stackoverflow.com/questions/8340922/what-does-a-bufferedreader-constructor-expect-a-filereader