How to Copy a File in Java: 6 Ways with Examples
Backups, versioned documents, downloaded updates and exported reports all involve copying data into a new file. Java provides a one-line method for the common case and several lower-level options when you need more control.
This tutorial shows every common way to copy files and folders in Java 25, each with a tested example.
1. What Is Copying a File in Java?
Copying a file creates a new file with exactly the same bytes as the original. A correct copy treats the content as bytes, never as text, so images, ZIP files and documents stay intact. Folders are not copied recursively by any single method; you copy them entry by entry.
2. Ways to Copy at a Glance
| Way | Best for | Since |
|---|---|---|
Files.copy(source, target) | Copying one file; the usual choice | Java 7 |
InputStream.transferTo() | Copying between any two streams | Java 9 |
| Buffer loop with streams | Progress reporting, very old Java versions | Java 1.0 |
Files.copy(inputStream, target) | Saving a download or resource to a file | Java 7 |
FileChannel.transferTo() | Large files, channel-based code | Java 1.4 |
Files.walk() + Files.copy() | Whole folders | Java 8 |
3. Using Files.copy()
A job seeker keeps a backup of their résumé before editing it.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class CopyWithFilesCopy {
public static void main(String[] args) throws IOException {
Path folder = Files.createTempDirectory("resume");
Path original = Files.writeString(folder.resolve("resume.txt"), "Java developer, 5 years\n");
Path backup = folder.resolve("resume-backup.txt");
Files.copy(original, backup);
System.out.println("Copied: " + (Files.mismatch(original, backup) == -1));
try {
Files.copy(original, backup); // target exists
} catch (FileAlreadyExistsException e) {
System.out.println("Without option: FileAlreadyExistsException");
}
Files.copy(original, backup, StandardCopyOption.REPLACE_EXISTING); // overwrite
System.out.println("With REPLACE_EXISTING: copied again");
Files.delete(backup);
Files.delete(original);
Files.delete(folder);
}
}
Copied: true Without option: FileAlreadyExistsException With REPLACE_EXISTING: copied again
How it works
Files.copy(source, target)copies the file;mismatch()confirms the copy is identical.- If the target already exists, it throws
FileAlreadyExistsException. StandardCopyOption.REPLACE_EXISTINGoverwrites the target;COPY_ATTRIBUTESwould also copy attributes such as the modified time.
4. Using InputStream.transferTo()
When you already work with streams, transferTo() copies everything in one call.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyWithTransferTo {
public static void main(String[] args) throws IOException {
Path song = Files.createTempFile("song", ".mp3");
Files.write(song, new byte[50_000]);
Path copy = Files.createTempFile("song-copy", ".mp3");
try (InputStream in = Files.newInputStream(song);
OutputStream out = Files.newOutputStream(copy)) {
long bytes = in.transferTo(out); // Java 9
System.out.println("Bytes copied: " + bytes);
}
System.out.println("Identical: " + (Files.mismatch(song, copy) == -1));
Files.delete(song);
Files.delete(copy);
}
}
Bytes copied: 50000 Identical: true
How it works
- Both streams are opened in one try-with-resources statement.
transferTo()(Java 9) copies all remaining bytes and returns the count.
5. Using a Buffer Loop
The classic copy loop works on every Java version and lets you report progress.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;
public class CopyWithBufferLoop {
public static void main(String[] args) throws IOException {
Path video = Files.createTempFile("clip", ".mp4");
Files.write(video, new byte[30_000]);
Path copy = Files.createTempFile("clip-copy", ".mp4");
long total = 0;
try (InputStream in = new BufferedInputStream(new FileInputStream(video.toFile()));
OutputStream out = new BufferedOutputStream(new FileOutputStream(copy.toFile()))) {
byte[] buffer = new byte[8192];
int n;
while ((n = in.read(buffer)) != -1) { // works on every Java version
out.write(buffer, 0, n);
total += n;
}
}
System.out.println("Bytes copied: " + total);
System.out.println("Identical: " + (Files.mismatch(video, copy) == -1));
Files.delete(video);
Files.delete(copy);
}
}
Bytes copied: 30000 Identical: true
How it works
read(buffer)returns the number of bytes read, or-1at the end.- Writing exactly
nbytes keeps the copy identical, even when the last read is shorter.
6. Saving an InputStream to a File
An updater saves a downloaded file. Here a ByteArrayInputStream stands in for the download.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyFromStream {
public static void main(String[] args) throws IOException {
// The source can be any InputStream: a download, a ZIP entry, a resource in a JAR ...
InputStream download = new ByteArrayInputStream("version=3.2\n".getBytes(StandardCharsets.UTF_8));
Path target = Files.createTempDirectory("updates").resolve("version.properties");
long bytes = Files.copy(download, target); // stream -> file
System.out.println("Saved " + bytes + " bytes: " + Files.readString(target).strip());
Files.delete(target);
Files.delete(target.getParent());
}
}
Saved 12 bytes: version=3.2
How it works
Files.copy(InputStream, Path)writes the whole stream to a new file and returns the byte count.- The same call saves resources from a JAR or entries from a ZIP file.
7. Using FileChannel.transferTo()
NIO channels can transfer data between files, letting the operating system do the work where possible.
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class CopyWithFileChannel {
public static void main(String[] args) throws IOException {
Path archive = Files.createTempFile("archive", ".zip");
Files.write(archive, new byte[100_000]);
Path copy = Files.createTempFile("archive-copy", ".zip");
try (FileChannel from = FileChannel.open(archive, StandardOpenOption.READ);
FileChannel to = FileChannel.open(copy, StandardOpenOption.WRITE)) {
long position = 0, size = from.size();
while (position < size) { // transferTo may copy less than asked
position += from.transferTo(position, size - position, to);
}
System.out.println("Bytes copied: " + position);
}
System.out.println("Identical: " + (Files.mismatch(archive, copy) == -1));
Files.delete(archive);
Files.delete(copy);
}
}
Bytes copied: 100000 Identical: true
How it works
FileChannel.open()opens the source for reading and the target for writing.transferTo()may copy fewer bytes than requested, so the loop continues until everything is copied.
8. Copying a Whole Folder
A website backup copies a folder with its sub-folders and files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class CopyFolder {
public static void main(String[] args) throws IOException {
Path site = Files.createTempDirectory("site");
Files.createDirectories(site.resolve("css"));
Files.writeString(site.resolve("index.html"), "<h1>Shop</h1>");
Files.writeString(site.resolve("css").resolve("style.css"), "h1 { color: teal; }");
Path backup = site.resolveSibling(site.getFileName() + "-backup");
List<Path> sources;
try (Stream<Path> tree = Files.walk(site)) { // parents come before their contents
sources = tree.toList();
}
for (Path source : sources) {
Files.copy(source, backup.resolve(site.relativize(source))); // a folder copy creates an empty folder
}
try (Stream<Path> copied = Files.walk(backup)) {
System.out.println("Paths in backup: " + copied.count());
}
System.out.println("CSS copied: " + Files.readString(backup.resolve("css").resolve("style.css")));
for (Path root : new Path[] {site, backup}) {
try (Stream<Path> tree = Files.walk(root)) {
for (Path p : tree.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
}
}
Paths in backup: 4
CSS copied: h1 { color: teal; }
How it works
Files.walk()lists the folder before its contents, so parent folders are created first.relativize()andresolve()map each source path to the matching backup path.- Copying a folder with
Files.copy()creates an empty folder; its entries are copied separately.
9. Common Mistakes and Best Practices
- Copying binary files with readers and writers. Decoding as text corrupts them; copy bytes.
- Forgetting
REPLACE_EXISTING. The copy fails when the target exists. - Expecting
Files.copy()to copy folder contents. Walk the tree instead. - Writing the whole buffer in a manual loop. Write only the bytes read.
- Copying a file onto itself. Check that source and target are different paths.
10. Summary
Files.copy()is the simplest way to copy a file.- Use
REPLACE_EXISTINGto overwrite andCOPY_ATTRIBUTESto keep metadata. transferTo()copies between any streams;Files.copy(InputStream, Path)saves a stream.- Copy folders entry by entry with
Files.walk(). - Always copy bytes, never decoded text.