Copying files from one directory to another in Java
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Java, copying files from one directory to another is easiest with the java.nio.file API. The basic case is copying one file to a destination path, but real applications often need to create missing directories, overwrite existing files deliberately, and sometimes copy an entire directory tree.
The important distinction is whether you are copying one file or recursively copying many files. Files.copy handles the first case directly, while recursive directory copy needs traversal logic.
Copy a Single File with Files.copy
For most code, Path plus Files.copy is the right starting point.
This example does three important things:
- builds paths with
Pathinstead of string concatenation - creates the destination directory if it does not exist
- uses
REPLACE_EXISTINGso the copy behavior is explicit
Without REPLACE_EXISTING, the copy fails when the target file is already present.
Copy Every File in a Directory Tree
If you want to copy one directory into another, you need to walk the source tree and rebuild the same relative structure under the destination.
The key step is relativize. It preserves the structure of nested folders instead of flattening every file into one destination directory.
When the Old Stream-Based Approach Still Matters
Before java.nio.file, developers copied files with InputStream and OutputStream. That still works, but it is more verbose and easier to get wrong.
Use this only when you have a specific reason to work at the stream level. For ordinary filesystem copies, Files.copy is clearer.
Preserve Metadata Only When You Need It
Copying file content is not the same as copying timestamps, permissions, or ownership. If metadata matters, add the appropriate copy options and test on the actual target platform.
For many application-level tasks, content plus filename is enough. For backup or deployment tooling, metadata may matter a lot.
Common Pitfalls
- Trying to copy into a directory that does not exist. Create the destination directories first.
- Copying a whole tree without preserving relative paths, which flattens filenames and causes collisions.
- Forgetting
REPLACE_EXISTINGand then treating a file-already-exists failure like a random I/O issue. - Using manual stream code when
Files.copywould be shorter, safer, and easier to maintain. - Assuming file metadata is preserved automatically when only file bytes were copied.
Summary
- Use
PathandFiles.copyfor most Java file-copy tasks. - Create missing destination directories explicitly.
- Use
Files.walkplusrelativizeto copy directory trees correctly. - Prefer
java.nio.fileover old stream-based code unless you need low-level control. - Decide intentionally whether overwriting and metadata preservation are part of the requirement.

