Course contentsShow
← Java
Lesson 1936 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Custom Buffer Sizes: Constructor Overload

Pass a buffer size to the BufferedInputStream/BufferedOutputStream constructor for specialized use cases.

Custom Buffer Sizes: Constructor Overload

You'll learn how to tune buffered stream performance by specifying custom buffer sizes instead of relying on the default 8KB.

The Core Idea

While BufferedInputStream and BufferedOutputStream use an 8KB buffer by default (which works well for most scenarios), Java lets you specify a custom buffer size through constructor overloads. This is useful when you have specialized requirements—like reading very large files where a bigger buffer reduces system calls even further, or handling tiny files where an 8KB buffer wastes memory.

Think of it like choosing a shopping cart size. The standard cart (8KB) works for most grocery trips, but if you're buying supplies for a restaurant, you might want a bigger cart. Conversely, if you're just grabbing a snack, a basket (smaller buffer) is more appropriate.

The Constructor Syntax

Both buffered stream classes offer constructors that accept an int buffer size parameter:

BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream out, int size)

The size parameter specifies the buffer size in bytes.

Example: Custom Buffer Size

FileInputStream fis = new FileInputStream("largefile.bin");
BufferedInputStream bis = new BufferedInputStream(fis, 65536); // 64KB buffer

FileOutputStream fos = new FileOutputStream("output.bin");
BufferedOutputStream bos = new BufferedOutputStream(fos, 32768); // 32KB buffer

// Use streams as normal
byte[] data = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(data)) != -1) {
    bos.write(data, 0, bytesRead);
}

bos.close();
bis.close();

Here, we've allocated a 64KB buffer for reading and a 32KB buffer for writing—both larger than the default 8KB.

Key Takeaway: Use the constructor overload BufferedInputStream(InputStream, int) and BufferedOutputStream(OutputStream, int) to specify custom buffer sizes when performance profiling or memory constraints demand tuning beyond the default 8KB.