I saw in a tutorial that the int read(byte b [], int off, int len) in the BufferedInputStream class itself uses the read() method to read data.
So my question is, what is the difference between the normal mode and without using BufferedInputStream with using buffer? The buffer was supposed to read bytes in blocks to reduce costs, but here it is reading byte by byte.
CodePudding user response:
It's true that the simplest concrete InputStream
is only required to implement just the method that reads a single byte (i.e. the InputStream.read()
method).
It's also true that for such an underlying InputStream
using a BufferedInputStream
doesn't have any performance benefit, because BufferedInputStream.read(byte b [], int off, int len)
depends on InputStream.read(byte b [], int off, int len)
which (in InputStream
) depends on the InputStream.read()
method.
However
Many (most) of the "typical" InputStream
subclasses that are used (for example java.io.FileInputStream
for reading files, java.net.SocketInputStream
for reading from network connections, java.util.zip.ZipFile.ZipFileInputStrem
for reading data from zip files) do implement the read(byte b [], int off, int len)
method.
For all these InputStream
subclasses using a BufferedInputStream
provides a tremendous performance benefit when reading single bytes (i.e. calling the read()
method) because these classes do either a system call for fetching a single byte (FileInputStream
), others allocate a byte array of length one and call read(byte[] b)
(which in turn calls read(b, 0, b.length)
) to read a single byte (SocketInputStream
, ZipFileInputStream
).
Note: the project that I used as base to find InputStream
subclasses has 326 different InputStream
subclasses. I didn't check every one of them to decide whether BufferedInputStream
is beneficial on them, I just checked those few that I tend to use.