BufferedInputStream: Creating an Internal Buffer
You'll learn: How to wrap a FileInputStream with BufferedInputStream to read data in chunks, dramatically reducing expensive system calls.
The Core Problem
In the previous lesson, you learned that reading files byte-by-byte with FileInputStream triggers a system call for every single byte—like making a trip to the warehouse for each individual screw. This is painfully slow.
The BufferedInputStream Solution
BufferedInputStream acts as a smart middleman between your code and the file. When you create one, it allocates an internal buffer (a byte array in memory). Instead of reading one byte at a time from the disk, it reads a large chunk—often 8,192 bytes—into this buffer in a single system call. Then it serves bytes to your program directly from memory.
Think of it like buying screws in bulk: one trip to the warehouse fills your toolbox, then you grab screws from your toolbox as needed.
Creating a BufferedInputStream
You wrap an existing FileInputStream:
FileInputStream fis = new FileInputStream("data.bin");
BufferedInputStream bis = new BufferedInputStream(fis);
Now when you call bis.read(), it returns bytes from the buffer. When the buffer empties, BufferedInputStream automatically refills it with another chunk from the file—invisibly to you.
You can also specify a custom buffer size:
BufferedInputStream bis = new BufferedInputStream(fis, 16384); // 16 KB buffer
What Happens Behind the Scenes
- First
read()call → BufferedInputStream reads 8,192 bytes from disk into its internal buffer - Next 8,191 calls → served directly from memory (blazing fast)
- 8,193rd call → refills buffer from disk automatically
Key Takeaway: BufferedInputStream wraps a FileInputStream and creates an internal byte buffer, reading file data in large chunks to minimize system calls while still letting you read byte-by-byte from memory.