Buffered Copying with Byte Arrays
What you'll learn: How to dramatically improve file copy performance by reading and writing chunks of bytes instead of one byte at a time.
The Problem with Byte-by-Byte Copying
In the previous lesson, you learned to copy files one byte at a time using read() and write(int). This works, but it's slow—imagine moving a pile of sand one grain at a time versus using a bucket!
The Buffered Approach
Instead of reading and writing single bytes, you can use byte arrays as buffers. Think of a buffer as a temporary holding area—like a bucket that holds multiple bytes at once. You fill the bucket from the source file, then dump it into the destination file in one go.
Common buffer sizes are 1024 bytes (1 KB) or 8192 bytes (8 KB). These sizes balance memory usage and performance.
How It Works
FileInputStream in = new FileInputStream("source.txt");
FileOutputStream out = new FileOutputStream("copy.txt");
byte[] buffer = new byte[8192]; // 8 KB buffer
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
Here's what happens:
- Create a byte array to act as your buffer
- Use
read(byte[])to fill the buffer—it returns how many bytes were actually read - Use
write(byte[], int, int)to write exactly that many bytes from the buffer - Repeat until
read()returns-1(end of file)
Why This Is Faster
Reading/writing involves overhead (like asking the operating system for data). By processing 8192 bytes per request instead of 1, you reduce overhead by a factor of 8192! A file that took 10 seconds to copy might now take milliseconds.
Key Takeaway: Using byte array buffers (typically 1024–8192 bytes) with read(byte[]) and write(byte[], int, int) dramatically improves file copy performance by reducing I/O operations and overhead.