Copy a File in Java

beginner·  File Handling  ·  File I/O

Problem

Copying a file duplicates its bytes into a new file; the copy is independent, so later changes to one don't affect the other.

Copy original.txt to backup.txt, overwriting any old backup, and confirm the two files match.

Input
original.txt (3 lines)
Output
backup.txt, identical

Java Program

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class CopyFile { public static void main(String[] args) throws IOException { Path source = Paths.get("original.txt"); Path target = Paths.get("backup.txt"); Files.writeString(source, "Quarterly figures\nQ1: 120\nQ2: 135\n"); // \n keeps the size the same on every OS Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); // overwrite if backup.txt exists System.out.println("Copied " + Files.size(target) + " bytes"); System.out.println("Identical: " + (Files.mismatch(source, target) == -1)); // -1 means no differing byte Files.delete(source); Files.delete(target); } }

Output

Copied 34 bytes Identical: true

Core Logic

Files.copy performs the whole copy in one call, and Files.mismatch checks the result.

How It Works
  1. 1Files.writeString creates the source file with \n line endings, so its size is the same on every OS.
  2. 2Files.copy(source, target, REPLACE_EXISTING) copies it, overwriting an existing backup.
  3. 3Files.size(target) reports how many bytes were copied.
  4. 4Files.mismatch (Java 12+) returns -1 when the files are identical.
The 34-byte source becomes a 34-byte backup, and mismatch finds no differing byte.
💡

Key Point: Without REPLACE_EXISTING, copying onto an existing file throws FileAlreadyExistsException.

Key Concepts

Files.copy()StandardCopyOption.REPLACE_EXISTINGFiles.mismatch()

Approach 2: Using Input and Output Streams

Java
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CopyFileStreams { public static void main(String[] args) throws IOException { Path source = Paths.get("original.txt"); Path target = Paths.get("backup.txt"); Files.writeString(source, "Quarterly figures\nQ1: 120\nQ2: 135\n"); long copied = 0; try (InputStream in = new FileInputStream(source.toFile()); OutputStream out = new FileOutputStream(target.toFile())) { byte[] buffer = new byte[8192]; // copy in chunks instead of byte by byte int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); // write only the bytes actually read copied += read; } } System.out.println("Copied " + copied + " bytes"); System.out.println("Backup reads: " + Files.readAllLines(target)); Files.delete(source); Files.delete(target); } }

Output

Copied 34 bytes Backup reads: [Quarterly figures, Q1: 120, Q2: 135]

Core Logic

The manual version reads the source into a buffer and writes each chunk to the target — the loop that Files.copy runs for you.

How It Works
  1. 1Both streams are opened in one try-with-resources statement.
  2. 2in.read(buffer) fills up to 8 KB and returns how many bytes it read, or -1 at the end.
  3. 3out.write(buffer, 0, read) writes exactly those bytes.
  4. 4A running total counts the bytes copied.
The whole 34-byte file fits in one read, so the loop runs once and then sees -1.
💡

Key Point: Writing the whole buffer instead of just read bytes would append leftover garbage from earlier chunks — the classic bug in hand-written copy loops.

Key Concepts

FileInputStreamFileOutputStreambyte buffer

Interview Questions

How do you move a file instead of copying it?

Files.move(source, target, StandardCopyOption.REPLACE_EXISTING). Within one disk this is usually a fast rename.

How do you copy a whole folder?

Files.copy copies a single file. To copy a folder, walk it with Files.walk and copy each file, creating subfolders as you go.

Learn the Concept

Related Programs