javafile-iostreamiostreambufferedinputstream

"BufferedInputStream" vs "FileInputStream with configured size"


Case 1 => BufferedInputStream is created and I would like to read() 12 bytes at a time, but it buffers upto 1024 bytes (say for instance) for performance improvement. So, it reads 1024 bytes in a single sys call USING the passed FileInputStream provided in BufferedInputStream constructor.

Case 2 => In FileInputStream.read(byte[]), I can pass a byte array of size 1024. Which means in each sys call, my FileInputStream reads 1024 bytes.

From Case 1 and Case 2, I cannot see any betterment BufferedInputStream provides in terms of run time performance. All it does is that wraps FileInputStream around and does the same what I did in Case 2.

can anyone help me understand better?


Solution

  • Yes, you can effectively re-implement what BufferedInputStream does by reading fixed blocks from the underlying InputStream, but it's not quite as easy:

    In the end BufferedInputStream is just pure Java code, so you can do anything it does manually as well, but there are very few reasons to do so.

    tl;dr BufferedInputStream is just a simple way to gain some performance by reducing system calls and buffering reads while still providing the normal InputStream interface. You could implement everything it provides without it, but there is almost never a reason to.