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

Buffering Both Input and Output

Understand that wrapping both FileInputStream and FileOutputStream with buffered variants dramatically improves bidirectional I/O.

Buffering Both Input and Output

What you'll learn: You'll discover how wrapping both FileInputStream and FileOutputStream with their buffered counterparts provides bidirectional performance gains when reading and writing simultaneously.

The Core Idea

When your program needs to read from one file while writing to another—or transforming data from input to output—you face I/O overhead on both sides of the operation. You've already learned that BufferedInputStream reduces read overhead and BufferedOutputStream reduces write overhead. The natural next step is combining them: wrap both streams to minimize system calls in both directions.

Think of it like warehouse operations. An unbuffered approach is like carrying one box at a time from the loading dock (input) to the shipping area (output)—lots of trips. Buffering both sides is like using a cart to collect boxes and staging them for efficient shipping—you optimize both the collection and delivery processes.

Why Both Matter

When copying or transforming files:

  • BufferedInputStream reads chunks from disk into memory, reducing read system calls
  • BufferedOutputStream accumulates output in memory before writing, reducing write system calls

Buffering just one side still leaves the other side making inefficient single-byte or small-array system calls. Buffering both eliminates this asymmetry.

The Pattern

try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("source.dat"));
     BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("dest.dat"))) {
    
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
    }
}

Both streams now use 8KB internal buffers (the default), dramatically reducing system calls compared to unbuffered equivalents.

Key Takeaway: Always buffer both input and output streams in bidirectional I/O operations to minimize system call overhead on both sides, achieving optimal throughput for file copying and transformation tasks.