Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Output, Background and Explanation of the code
To make life a bit easier, Java provides a “wrapper” input stream called BufferedInputStream. This is constructed around another base input stream such as FileInputStream, but buffers reads in the background. That is, we can call the single-byte version of read(), and BufferedInputStream will behind the scenes read multiple bytes from the file into a buffer and then serve us bytes from the buffer. This “wrapper” model means that we can add buffering with a single line of code.
As a general rule of thumb, you should always wrap an input stream in a BufferedInputStream except where you know there’s other buffering going on. For example, if you are calling the multi-byte reads on a FileInputStream and reading a reasonably large number of bytes (say, a few K) at a time, then adding an extra BufferedInputStream probably won’t give you much benefit and could even slow down your I/O slightly due to the extra buffer copying. But if you’re not sure, the penalty for not buffering is generally much greater than the penalty of an unnecessary extra layer of buffering.