Copying Files Byte by Byte
You'll learn how to implement a simple file copy operation using single-byte reads and writes, and why this approach has serious performance drawbacks.
The Core Idea
Copying a file byte by byte means reading one byte at a time from the source file using read() and immediately writing that single byte to the destination file using write(int). While conceptually straightforward, this is like moving a mountain one grain of sand at a time—it works, but it's painfully slow.
How It Works
You open a FileInputStream to read from the source and a FileOutputStream to write to the destination. Then you loop, reading one byte at a time until you reach end-of-file (when read() returns -1):
try (FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("copy.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
fos.write(byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
The Performance Problem
Each call to read() and write() involves overhead—disk I/O operations, system calls, and buffer management. For a 1 MB file, you'd make 1 million separate read calls and 1 million separate write calls. This is extremely inefficient compared to reading and writing larger chunks of data at once using byte arrays.
When You Might See This Pattern
This approach appears in educational examples to demonstrate the basic stream operations, but production code almost never uses single-byte copying. It's a stepping stone to understanding better techniques.
Key Takeaway: Byte-by-byte file copying works but suffers from severe performance issues due to excessive I/O operations; always prefer reading and writing byte arrays in chunks for practical applications.