To begin with, I understand the concept of buffering as a wrapper around, for example, FileInuptStream , to act as a temporary container for reading content (allowing you to take a reading script) from the base stream, in this case, FileInputStream .
- Say there are 100 bytes to read from the stream (file as source).
- Without buffering, the code (
read the BufferedInputStream method) should be 100 views (one byte at a time). - With buffering, depending on the size of the buffer, the code does <= 100.
- Suppose the buffer size is 50.
- Thus, the code reads the buffer (as a source) only twice to read the contents of the file.
- Now that
FileInuptStream is the final source (albeit wrapped by BufferedInputStream ) of data (a file that contains 100 bytes), does it need to read 100 times to read 100 bytes? Although the code calls the read BufferedInputStream method, the call is passed to the read FileInuptStream method, which needs to make 100 read calls. This is a moment that I cannot understand.
IOW, although wrapped in a BufferedInputStream , underlying streams (like FileInputStream ) still have to read one byte at a time. So, where is the advantage (not for code that requires only two reads for a buffer, but, to application performance) buffering?
Thanks.
EDIT:
I do this as a follow-up "edit", not a "comment", because, in my opinion, it is contextually better suited here as a TL; DR for chat readers between @Kayaman and me.
The read method of BufferedInputStream says (excerpt):
As an added convenience, it tries to read as many bytes as possible, repeatedly referring to the read base stream method. This repeat reading continues until one of the following conditions is met:
The specified number of bytes have been read, The read method of the underlying stream returns -1, indicating end-of-file, or The available method of the underlying stream returns zero, indicating that further input requests would block.
I dug up the code and found a trace of the method call as shown below:
BufferedInputStream read(byte b[]) How I want to see buffering in action.BufferedInputStream → read(byte b[], int off, int len)BufferedInputStream read1(byte[] b, int off, int len) - privateFileInputStream - read (byte b [], int off, int len)FileInputStream → readBytes(byte b[], int off, int len) - private and native. Description of the method from the source code -
Reads a submatrix as a sequence of bytes.
The call to read1 (# 4, above) in the BufferedInputStream is in an infinite for loop. It returns to the conditions specified in the above excerpt of the description of the read method.
As I mentioned in OP (# 6), the call seems to handle the underlying thread, which matches the API method description and the method call trace.
The question still remains if the built-in API call - readBytes of FileInputStream reads one byte at a time and creates an array of bytes returned?