Java Files: Copying, Moving, Deleting and Comparing Files (OCP 21)
Changing the file system with NIO.2 for the OCP 21 exam: Files.copy for files, directories and I/O streams, shallow versus deep copies, REPLACE_EXISTING, move and ATOMIC_MOVE, delete versus deleteIfExists, symbolic links, and comparing with isSameFile and mismatch.
kvi5hnuCode Sprout team member7 min readOn this page
Article 85 covered paths as names. This article covers changing what's actually on disk: copying, moving and deleting files and directories, and comparing them. These Files methods all declare IOException, and most of the exam questions are about exactly when they throw.
Copying with Files.copy()
public static Path copy(Path source, Path target, CopyOption... options) throws IOException
This copies a file or directory to the target path and returns the target.
Copying a directory is shallow
Copying a directory creates a new empty directory. Its files and subdirectories aren't copied. That's a shallow copy. For a deep copy of the whole tree, recurse yourself:
static void copyTree(Path source, Path target) throws IOException {
Files.copy(source, target); // the entry itself
if (Files.isDirectory(source)) {
try (Stream<Path> children = Files.list(source)) {
for (Path child : children.toList())
copyTree(child, target.resolve(child.getFileName()));
}
}
}
Files.walk() (article 91) is another way to visit every entry.
When the target exists
By default, copy() and move() refuse to overwrite. If the target exists, they throw FileAlreadyExistsException. To overwrite, pass StandardCopyOption.REPLACE_EXISTING:
Files.copy(cover, backupCover, StandardCopyOption.REPLACE_EXISTING);
Even with REPLACE_EXISTING, a non-empty directory can't be replaced. That throws DirectoryNotEmptyException. A missing parent directory for the target throws NoSuchFileException.
Other copy options:
COPY_ATTRIBUTEScopies metadata such as the last-modified time.LinkOption.NOFOLLOW_LINKScopies a symbolic link as a link. By default,copyfollows the link and copies the target's contents.
Copying a file into a directory
This is a favorite trap. Suppose the file cover.jpg and the directory shallow both exist:
Files.copy(cover, Path.of("shallow")); // FileAlreadyExistsException!
The target is the complete new path, not "the folder to put it in". Java tries to create an entry named shallow, which already exists. If shallow didn't exist, Java would create a file called shallow containing the image. Names don't need extensions. To copy into the directory, name the new file:
Files.copy(cover, Path.of("shallow").resolve(cover.getFileName())); // shallow/cover.jpg
move() follows exactly the same rule.

Copying with I/O streams
Two more overloads connect files and the java.io streams covered in article 87:
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
public static long copy(Path source, OutputStream out) throws IOException
Both return the number of bytes copied. The first saves any input stream, from a file, the network or memory, to a file. It also refuses to overwrite unless given REPLACE_EXISTING. The second writes a file's bytes to an output stream: Files.copy(path, System.out) prints a file.
Moving and renaming with Files.move()
public static Path move(Path source, Path target, CopyOption... options) throws IOException
Renaming is moving within the same directory:
Files.move(Path.of("backup"), Path.of("archive")); // rename a directory, contents included
Files.move(Path.of("raw.dat"), Path.of("archive/2024/raw-lake.dat")); // move and rename a file
- A directory keeps its contents when moved within the same file system. Moving a non-empty directory to a different file system or drive may fail, because it would need a copy.
- Like
copy(), it needsREPLACE_EXISTINGto overwrite, and it doesn't put a file into a target directory. StandardCopyOption.ATOMIC_MOVEmakes the move a single indivisible operation. Other processes see either the old state or the new one, never a partly moved file. If the file system can't do that, Java throwsAtomicMoveNotSupportedException.ATOMIC_MOVEbelongs toStandardCopyOption, but passing it tocopy()throwsUnsupportedOperationException.
Deleting with delete() and deleteIfExists()
public static void delete(Path path) throws IOException
public static boolean deleteIfExists(Path path) throws IOException
| Situation | delete | deleteIfExists |
|---|---|---|
| File or empty directory | deletes it | deletes it, returns true |
| Path doesn't exist | NoSuchFileException | returns false |
| Non-empty directory | DirectoryNotEmptyException | DirectoryNotEmptyException |
| Symbolic link | deletes the link, not its target | same |
To delete a tree, delete the deepest entries first: walk the tree and sort in reverse order, as the cleanup code in these examples does. deleteIfExists is the counterpart of createDirectories: it ensures something is gone without failing if it already was.
Comparing files
equals() only compares path text, so album/2024/../cover.jpg doesn't equal album/cover.jpg. Files has two methods that look at the disk.
isSameFile(): the same file?
public static boolean isSameFile(Path path, Path path2) throws IOException
- It resolves
.and..and follows symbolic links, then checks whether both paths locate the same file or directory. - If the two paths are
equals(), it returnstruewithout checking that the file exists. - Otherwise, a missing path throws
NoSuchFileException. - Two files with identical contents are still different files, so the result is
false.
mismatch(): the same contents?
public static long mismatch(Path path, Path path2) throws IOException
Added in Java 12, mismatch() compares contents byte by byte:
- it returns
-1if the contents are identical, which includes the case where both paths are the same file; - otherwise it returns the zero-based index of the first byte that differs;
- if one file is a prefix of the other, it returns the length of the shorter file;
- the result is the same whichever order you pass the paths in.
With "Harbor" and "Hamlet", the first difference is at index 2 (r versus m), so mismatch returns 2 both ways.
What's current
Files.mismatch()(Java 12) is the newest method in this group. Everything else dates from Java 7.- These methods are the same in Java 21 and 25. There's still no built-in recursive copy or delete, so you write the recursion yourself or use
Files.walk().
Exam traps from this article
A complete example
A photo library is backed up and reorganized in a temporary folder. The program shows a shallow copy next to a recursive deep copy and the overwrite rules. It walks through the copy-into-a-directory trap, copies with I/O streams, renames and moves (including an atomic move), deletes in every situation, and compares paths with equals, isSameFile and mismatch.
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
static Path root;
/** Lists everything under dir, relative to the temporary root, directories marked with '/'. */
static String tree(Path dir) throws IOException {
try (Stream<Path> all = Files.walk(dir)) {
return all.filter(p -> !p.equals(dir))
.map(p -> root.relativize(p) + (Files.isDirectory(p) ? "/" : ""))
.sorted().toList().toString();
}
}
/** Deep copy: Files.copy copies one entry; recursion copies what's inside directories. */
static void copyTree(Path source, Path target) throws IOException {
Files.copy(source, target);
if (Files.isDirectory(source)) {
try (Stream<Path> children = Files.list(source)) {
for (Path child : children.toList())
copyTree(child, target.resolve(child.getFileName()));
}
}
}
static void attempt(String label, IoAction action) {
try {
System.out.println(" " + label + ": " + action.run());
} catch (IOException | RuntimeException e) {
System.out.println(" " + label + " -> " + e.getClass().getSimpleName());
}
}
interface IoAction { Object run() throws IOException; }
public static void main(String[] args) throws IOException {
root = Files.createTempDirectory("photos").toRealPath();
try {
Path album = Files.createDirectories(root.resolve("album/2024"));
Files.writeString(album.resolve("lake.jpg"), "LAKE-PIXELS");
Files.writeString(album.resolve("hill.jpg"), "HILL-PIXELS");
Files.writeString(root.resolve("album/cover.jpg"), "COVER");
System.out.println("== Start: " + tree(root));
System.out.println("\n== 1. copy() is shallow for directories");
Files.copy(root.resolve("album"), root.resolve("shallow"));
System.out.println(" after Files.copy(album, shallow): shallow contains " + tree(root.resolve("shallow")));
copyTree(root.resolve("album"), root.resolve("backup"));
System.out.println(" after a recursive copy: " + tree(root.resolve("backup")));
System.out.println("\n== 2. Copying onto something that exists");
Path cover = root.resolve("album/cover.jpg");
attempt("copy(cover, backup/cover.jpg)", () -> Files.copy(cover, root.resolve("backup/cover.jpg")));
Files.writeString(cover, "NEW-COVER");
attempt("same with REPLACE_EXISTING", () -> Files.readString(
Files.copy(cover, root.resolve("backup/cover.jpg"), StandardCopyOption.REPLACE_EXISTING)));
System.out.println("\n== 3. A file can't be copied INTO a directory by naming the directory");
attempt("copy(cover, shallow)", () -> Files.copy(cover, root.resolve("shallow")));
attempt("copy(cover, shallow.resolve(cover.getFileName()))",
() -> root.relativize(Files.copy(cover, root.resolve("shallow").resolve(cover.getFileName()))));
attempt("copy(cover, prints) where prints doesn't exist",
() -> "created FILE named " + root.relativize(Files.copy(cover, root.resolve("prints")))
+ ", isRegularFile=" + Files.isRegularFile(root.resolve("prints")));
System.out.println("\n== 4. Copying with I/O streams");
try (InputStream in = new ByteArrayInputStream("CAMERA-RAW".getBytes())) {
System.out.println(" copy(InputStream, Path) wrote " + Files.copy(in, root.resolve("raw.dat")) + " bytes");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
long n = Files.copy(root.resolve("raw.dat"), out);
System.out.println(" copy(Path, OutputStream) read " + n + " bytes: " + out);
System.out.println("\n== 5. move() renames and relocates; directories keep their contents");
Files.move(root.resolve("backup"), root.resolve("archive"));
System.out.println(" backup renamed to archive: " + tree(root.resolve("archive")));
Files.move(root.resolve("raw.dat"), root.resolve("archive/2024/raw-lake.dat"), StandardCopyOption.ATOMIC_MOVE);
System.out.println(" raw.dat moved atomically: " + Files.exists(root.resolve("archive/2024/raw-lake.dat")));
attempt("move onto an existing file", () -> Files.move(root.resolve("prints"), root.resolve("archive/cover.jpg")));
attempt("copy(..., ATOMIC_MOVE)", () -> Files.copy(cover, root.resolve("x.jpg"), StandardCopyOption.ATOMIC_MOVE));
System.out.println("\n== 6. delete() and deleteIfExists()");
attempt("delete a non-empty directory", () -> { Files.delete(root.resolve("archive")); return "deleted"; });
attempt("delete a missing file", () -> { Files.delete(root.resolve("ghost.jpg")); return "deleted"; });
attempt("deleteIfExists(missing)", () -> Files.deleteIfExists(root.resolve("ghost.jpg")));
attempt("deleteIfExists(prints)", () -> Files.deleteIfExists(root.resolve("prints")));
Path link = Files.createSymbolicLink(root.resolve("latest"), cover);
Files.delete(link);
System.out.println(" deleting a symbolic link keeps its target: " + Files.exists(cover));
System.out.println("\n== 7. isSameFile(): same file on disk?");
Path viaDots = root.resolve("album/2024/../cover.jpg");
System.out.println(" album/cover.jpg vs album/2024/../cover.jpg: equals=" + cover.equals(viaDots)
+ ", isSameFile=" + Files.isSameFile(cover, viaDots));
Path alias = Files.createSymbolicLink(root.resolve("fav"), album);
System.out.println(" album/2024 vs symbolic link fav: " + Files.isSameFile(album, alias));
System.out.println(" two copies with equal bytes: "
+ Files.isSameFile(root.resolve("album/2024/lake.jpg"), root.resolve("archive/2024/lake.jpg")));
Path ghost = Path.of("ghost/none.jpg");
System.out.println(" equal paths, file missing: " + Files.isSameFile(ghost, ghost) + " (not even checked)");
attempt("different missing paths", () -> Files.isSameFile(ghost, Path.of("ghost/other.jpg")));
System.out.println("\n== 8. mismatch(): compare contents");
Path lake = root.resolve("album/2024/lake.jpg"), hill = root.resolve("album/2024/hill.jpg");
System.out.println(" lake.jpg vs its copy: " + Files.mismatch(lake, root.resolve("archive/2024/lake.jpg")));
System.out.println(" LAKE-PIXELS vs HILL-PIXELS: " + Files.mismatch(lake, hill)
+ ", reversed: " + Files.mismatch(hill, lake));
Path shortOne = Files.writeString(root.resolve("short.jpg"), "LAKE");
System.out.println(" LAKE-PIXELS vs LAKE: " + Files.mismatch(lake, shortOne) + " (length of the shorter file)");
} finally {
try (Stream<Path> all = Files.walk(root)) {
for (Path p : all.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
System.out.println("\n temporary directory removed: " + Files.notExists(root));
}
}
Output:
== Start: [album/, album/2024/, album/2024/hill.jpg, album/2024/lake.jpg, album/cover.jpg]
== 1. copy() is shallow for directories
after Files.copy(album, shallow): shallow contains []
after a recursive copy: [backup/2024/, backup/2024/hill.jpg, backup/2024/lake.jpg, backup/cover.jpg]
== 2. Copying onto something that exists
copy(cover, backup/cover.jpg) -> FileAlreadyExistsException
same with REPLACE_EXISTING: NEW-COVER
== 3. A file can't be copied INTO a directory by naming the directory
copy(cover, shallow) -> FileAlreadyExistsException
copy(cover, shallow.resolve(cover.getFileName())): shallow/cover.jpg
copy(cover, prints) where prints doesn't exist: created FILE named prints, isRegularFile=true
== 4. Copying with I/O streams
copy(InputStream, Path) wrote 10 bytes
copy(Path, OutputStream) read 10 bytes: CAMERA-RAW
== 5. move() renames and relocates; directories keep their contents
backup renamed to archive: [archive/2024/, archive/2024/hill.jpg, archive/2024/lake.jpg, archive/cover.jpg]
raw.dat moved atomically: true
move onto an existing file -> FileAlreadyExistsException
copy(..., ATOMIC_MOVE) -> UnsupportedOperationException
== 6. delete() and deleteIfExists()
delete a non-empty directory -> DirectoryNotEmptyException
delete a missing file -> NoSuchFileException
deleteIfExists(missing): false
deleteIfExists(prints): true
deleting a symbolic link keeps its target: true
== 7. isSameFile(): same file on disk?
album/cover.jpg vs album/2024/../cover.jpg: equals=false, isSameFile=true
album/2024 vs symbolic link fav: true
two copies with equal bytes: false
equal paths, file missing: true (not even checked)
different missing paths -> NoSuchFileException
== 8. mismatch(): compare contents
lake.jpg vs its copy: -1
LAKE-PIXELS vs HILL-PIXELS: 0, reversed: 0
LAKE-PIXELS vs LAKE: 4 (length of the shorter file)
temporary directory removed: true
Points to notice:
Files.copy(album, shallow)created an empty directory. Only the recursive method copied the photos.- Copying onto an existing file failed until
REPLACE_EXISTINGwas added. - Copying
cover.jpgto the existing directoryshallowfailed, and copying to the missing nameprintscreated a file calledprints. Files.copywith streams returned the byte count: 10 forCAMERA-RAW.isSameFilesaidtruefor a path through..and for a symbolic link, butfalsefor two copies with identical bytes.mismatchsaid-1for those.mismatchreturned0forLAKE-PIXELSandHILL-PIXELS, because they differ at the very first byte.
Common questions
Is there a Files method that deletes a whole directory tree?
No. Walk the tree, delete files first, then their directories. Sorting the walked paths in reverse order does that.
Why does copy follow symbolic links by default?
Usually you want the data, not the pointer. Pass LinkOption.NOFOLLOW_LINKS to copy the link itself.
Do copy and move create missing parent directories?
No. Call Files.createDirectories(target.getParent()) first, or you'll get NoSuchFileException.
Summary
Files.copy(source, target)copies one file or a shallow directory. Recurse for a deep copy. The stream overloads copy to or fromInputStream/OutputStreamand return byte counts.Files.move(source, target)moves or renames.ATOMIC_MOVEmakes it indivisible.- Both throw
FileAlreadyExistsExceptionfor an existing target unlessREPLACE_EXISTINGis used, and the target is always the new entry's full name. delete()throws for missing paths, whiledeleteIfExists()returnsfalse. Neither deletes non-empty directories.isSameFile()compares identity on disk.mismatch()compares contents and returns-1or the first differing index.
Practice quiz
Test yourself with the copy, move and delete quiz: 10 exam-style questions with explanations.
Previous: Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)
Next: Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
Related reading
- Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)
- Java File and Path: Creating Paths and Converting Between Them (OCP 21)
- Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
- Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
- Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.