Sub topic 13
Copying, Moving and Deleting Files
This chapter covers the Files methods that copy, move and delete files and directories. It assumes you can build a Path, read basic file attributes, and handle checked exceptions. You should also know that Files.exists and Files.isDirectory exist. Java 11 or later is needed.
The three operations
Files.copy, Files.move and Files.delete work on one path at a time. They do not look inside directories. That detail causes most of the surprises in this chapter.
| Method | What it does | Default if the target exists |
|---|---|---|
| `Files.copy(source, target, options...)` | Copies a file or creates an empty directory at the target | Throws `FileAlreadyExistsException` |
| `Files.move(source, target, options...)` | Renames or relocates a file or directory | Throws `FileAlreadyExistsException` |
| `Files.delete(path)` | Removes a file or an empty directory | Throws `NoSuchFileException` if missing |
| `Files.deleteIfExists(path)` | Same as `delete`, but returns `false` if the path is missing | Returns `false` |
The default is to refuse to overwrite. You must opt in to overwriting with a copy option.
Copying files
The simplest copy takes two paths:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class CopyDemo {
public static void main(String[] args) throws IOException {
Path source = Path.of("source.txt");
Path target = Path.of("backup.txt");
Files.writeString(source, "hello\n");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println(Files.readString(target));
}
}Run this twice. Without REPLACE_EXISTING the second run fails, because backup.txt already exists.
StandardCopyOption has three values:
REPLACE_EXISTINGoverwrites the target. If the target is a non-empty directory, the call fails withDirectoryNotEmptyException.COPY_ATTRIBUTESalso copies attributes such as the last modified time. Which attributes survive depends on the file system.ATOMIC_MOVEapplies only tomove. Passing it tocopythrowsUnsupportedOperationException.
REPLACE_EXISTING on a symbolic link replaces the link itself, not the file it points to. Copying a symbolic link copies the target's content by default. Add LinkOption.NOFOLLOW_LINKS if you want the link itself.
Copying between streams and files
Files.copy has two other overloads. They connect a file to an InputStream or OutputStream:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class StreamCopy {
public static void main(String[] args) throws IOException {
Path file = Path.of("sample.txt");
Files.writeString(file, "stream me\n");
ByteArrayOutputStream out = new ByteArrayOutputStream();
long written = Files.copy(file, out);
System.out.println(written + " bytes: " + out.toString());
try (InputStream in = new java.io.ByteArrayInputStream("new content\n".getBytes())) {
Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
}
System.out.println(Files.readString(file));
}
}Both overloads return the number of bytes copied. They move raw bytes, so no charset is involved. The stream-to-file overload refuses to overwrite unless you pass REPLACE_EXISTING, just like the path version. It does not close the stream. In the example, try-with-resources does that.
Copying a directory is shallow
Copying a directory creates an empty directory at the target. The contents are not copied:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ShallowCopy {
public static void main(String[] args) throws IOException {
Path src = Path.of("srcDir");
Files.createDirectories(src);
Files.writeString(src.resolve("a.txt"), "a\n");
Path dst = Path.of("dstDir");
Files.copy(src, dst);
System.out.println(Files.isDirectory(dst));
try (var children = Files.list(dst)) {
System.out.println(children.count());
}
}
}The second line prints 0. To copy a whole tree, walk the source and copy each entry, mapping its path onto the target. This pattern uses relativize and resolve from the earlier path chapters:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
public class TreeCopy {
static void copyTree(Path source, Path target) throws IOException {
try (Stream<Path> paths = Files.walk(source)) {
for (Path p : (Iterable<Path>) paths::iterator) {
Path dest = target.resolve(source.relativize(p).toString());
if (Files.isDirectory(p)) {
Files.createDirectories(dest);
} else {
Files.copy(p, dest, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
public static void main(String[] args) throws IOException {
copyTree(Path.of("srcDir"), Path.of("treeCopy"));
}
}Files.walk visits a directory before its children, so each destination directory exists before its files are copied. The toString() call avoids a ProviderMismatchException if the two paths ever belong to different file systems, such as a ZIP file system.
Moving and renaming
Files.move covers both renaming and relocating. Renaming is a move within the same directory:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class MoveDemo {
public static void main(String[] args) throws IOException {
Path draft = Path.of("draft.txt");
Files.writeString(draft, "text\n");
Path published = draft.resolveSibling("published.txt");
Files.move(draft, published, StandardCopyOption.REPLACE_EXISTING);
System.out.println(Files.exists(draft));
System.out.println(Files.exists(published));
}
}This prints false then true. resolveSibling replaces the last name element, which is convenient for renames.
What happens inside a move
The behavior depends on whether source and target are on the same file system.
A rename on the same file store is cheap and does not touch file contents. Across different file stores, the move becomes a copy followed by a delete. A crash in between can leave both files present. With ATOMIC_MOVE the operation either completes fully or throws, so no partial state is observable. Other options are ignored when ATOMIC_MOVE is present, and whether an existing target is replaced is then implementation specific.
A directory can be moved only if it is empty or the move is a rename within the same store. Moving a non-empty directory across stores throws DirectoryNotEmptyException, because the copy step would be shallow and deleting the source would lose data.
Deleting
Files.delete removes a file or an empty directory:
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class DeleteDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("temp.txt");
Files.writeString(file, "x");
Files.delete(file);
try {
Files.delete(file);
} catch (NoSuchFileException e) {
System.out.println("Already gone: " + e.getFile());
}
System.out.println(Files.deleteIfExists(file));
Path dir = Path.of("full");
Files.createDirectories(dir);
Files.writeString(dir.resolve("a.txt"), "a");
try {
Files.delete(dir);
} catch (DirectoryNotEmptyException e) {
System.out.println("Not empty: " + e.getFile());
}
}
}Use deleteIfExists when a missing file is acceptable. It is also safer than checking Files.exists first, because another process could remove the file between your check and your delete.
Deletion bypasses any recycle bin or trash. A successful delete is permanent.
Deleting a tree
Like copy, delete is shallow. To remove a directory tree, delete the children before their parent. Files.walk lists parents first, so sort the paths in reverse order:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;
public class TreeDelete {
static void deleteTree(Path root) throws IOException {
try (Stream<Path> paths = Files.walk(root)) {
for (Path p : (Iterable<Path>) paths.sorted(Comparator.reverseOrder())::iterator) {
Files.delete(p);
}
}
}
public static void main(String[] args) throws IOException {
deleteTree(Path.of("treeCopy"));
}
}Reverse lexicographic order works because a parent path is always a prefix of its children, so each child sorts before its parent. Do not use forEach(Files::delete) here. Files.delete throws a checked exception, which the lambda cannot propagate. A FileVisitor with Files.walkFileTree is the other common choice, and it gives you hooks for handling failures per entry.
Failure modes to expect
| Exception | Typical cause |
|---|---|
| `FileAlreadyExistsException` | Target exists and `REPLACE_EXISTING` was not given |
| `NoSuchFileException` | Source is missing, or the target's parent directory does not exist |
| `DirectoryNotEmptyException` | Deleting or replacing a non-empty directory |
| `AccessDeniedException` | Missing permission, or on Windows the file is open in another process |
| `AtomicMoveNotSupportedException` | `ATOMIC_MOVE` requested across stores or on an unsupported file system |
All of these extend FileSystemException, which extends IOException. Catch the specific ones when you can recover, and let the rest propagate.
Neither copy nor move creates missing parent directories. Call Files.createDirectories(target.getParent()) first when the target folder may not exist. Note that getParent() returns null for a bare file name such as Path.of("a.txt"), so use toAbsolutePath().getParent() when in doubt.
Summary of decisions
- Use
copywithREPLACE_EXISTINGwhen overwriting is intended, and without it when a collision is a bug. - Use
movefor renames. AddATOMIC_MOVEwhen no one may observe an intermediate state, and be ready forAtomicMoveNotSupportedException. - Use
deleteIfExistswhen absence is fine, and delete trees child-first. - Remember that all three operations are shallow for directories.
Exercise
You call Files.copy(Path.of("photos"), Path.of("photos-backup")) on a directory that holds 50 files. The call succeeds. What does photos-backup contain, and what would you change to back up everything?
Show answer
It is an empty directory. Files.copy on a directory copies only the directory entry, not its contents. To back up everything, walk the source with Files.walk, and for each path compute the destination with target.resolve(source.relativize(p).toString()). Create directories with Files.createDirectories and copy regular files with Files.copy, passing REPLACE_EXISTING if overwriting is acceptable.
Exercise
A deleteTree method uses Files.walk(root).forEach(Files::delete) and fails. Give two reasons it is wrong and the fix.
Show answer
First, Files.delete throws the checked IOException, so the method reference does not compile as a Consumer. Second, even with the exception handled, walk lists a directory before its children, so the delete of the directory fails with DirectoryNotEmptyException. Sort the stream with Comparator.reverseOrder() so children come first, and delete in a loop that can propagate IOException. Close the stream with try-with-resources.
Exercise
You move report.tmp to report.txt in another mounted drive using StandardCopyOption.ATOMIC_MOVE and get AtomicMoveNotSupportedException. Why, and what are your options?
Show answer
An atomic move is a single rename, which is possible only within one file store. A different drive requires copying the bytes and deleting the source. Either create the temporary file on the same drive as the final target, which keeps the atomic move, or drop ATOMIC_MOVE and accept that a crash during the copy can leave partial or duplicate files.