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

Copying Files: A Complete Example with FileInputStream and FileOutputStream

Build a practical file copy utility combining FileInputStream and FileOutputStream with proper resource management.

Copying Files: A Complete Example with FileInputStream and FileOutputStream

You'll learn how to build a practical file copy utility that reads from one file and writes to another using the byte streams you've been studying.

The Complete Picture

Now that you've learned the individual pieces—reading with FileInputStream and writing with FileOutputStream—let's put them together for a real-world task: copying a file. This combines everything you've practiced: creating streams, reading bytes into an array, writing those bytes to another file, and properly managing resources.

Think of it like transferring water from one bucket to another using a cup. You repeatedly scoop water from the source bucket (FileInputStream) and pour it into the destination bucket (FileOutputStream) until the source is empty.

Building the Copy Utility

import java.io.*;

public class FileCopyExample {
    public static void main(String[] args) {
        String sourceFile = "original.txt";
        String destFile = "copy.txt";
        
        FileInputStream fis = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(destFile);
            
            byte[] buffer = new byte[1024]; // 1KB buffer
            int bytesRead;
            
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            
            fos.flush();
            System.out.println("File copied successfully!");
            
        } catch (IOException e) {
            System.err.println("Error copying file: " + e.getMessage());
        } finally {
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                System.err.println("Error closing streams: " + e.getMessage());
            }
        }
    }
}

The key pattern: read chunks into a buffer, then immediately write those exact bytes. The loop continues until read() returns -1, signaling end-of-file. Notice we write only bytesRead bytes—the last chunk might not fill the entire buffer.

Key Takeaway: A file copy combines FileInputStream for reading and FileOutputStream for writing, using a buffer for efficiency and proper finally blocks to ensure both streams are closed even if errors occur.