What the BufferedReader constructor expects FileReader

I need to understand the difference between the two classes and how they work with each other. I understand that FileReader reads characters from a file one character at a time, and BufferedReader reads a large chunk of data and saves it in the buffer, and thereby makes it faster.

To use BufferedReader, I have to provide it with a FileReader. How does the BufferedReader class use FileReader if it reads a file in different ways? Does this mean that BufferedReader uses FileReader, and so behind the scenes characters are still reading one character at a time? I guess my question is how the BufferedReader class uses the FileReader class.

+6
source share
4 answers

First of all, BufferedReader accepts a Reader , not a FileReader (although the latter is accepted).

The abstract Reader class has several read() methods. There is a single-character version, as well as two versions that read a block of characters into an array.

It makes sense to use BufferedReader if you are reading single characters or small blocks at a time.

Consider the following two queries:

 char ch1 = fileReader.read(); char ch2 = bufferedReader.read() 

The first of them will go to the base file, and the second will most likely be executed from the internal BufferedReader buffer.

+5
source

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.

BufferedReader makes reading the size you need and still efficient. If you always read large blocks, it might be a little more efficient to reset the BufferedReader.

+6
source

FileReader has the ability to read fragments, and not just 1 character at a time. It inherits the read (char []) methods from Reader so that you can read the size of the char [] array that you are passing. BufferedReader simply wraps FileReader, so when you call read () in BufferedReader, it processes the internal buffers and calls read () methods in its base Reader. One of the main reasons for using BufferedReader is to use the readLine () method. BufferedReader can wrap readers other than FileReader (e.g., InputStreamReader).

+2
source

BufferedReader adds a buffering layer on top of any reader. The point is to make reading more optimal than reading a file, socket, or something in an unbuffered way. He also adds some convenient methods that will not work very well, unless he precedes you a piece. In the case of the FileReader, you have to read the data fragment until you find "\ n" in order to be able to do something like BufferedReader.readLine (), and then you have to leave the rest of the data for the next read operation (not to mention the work necessary when you need to wait for a slow data source to deliver all this to you).

+2
source

Source: https://habr.com/ru/post/902837/


All Articles