Sub topic 13
Copying, Moving, and Deleting Files
This chapter assumes basic Java syntax, Path, Files, checked exceptions, and try-with-resources. It also assumes Java 11 or later. The java.nio.file API represents locations with Path and performs file operations through the Files utility class.
Copying files
Use Files.copy when the original should remain unchanged. The simplest form copies a file to a new location:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileOperations {
public static void main(String[] args) throws IOException {
Path source = Path.of("notes.txt");
Path backup = Path.of("backup", "notes.txt");
Files.createDirectories(backup.getParent());
Files.copy(source, backup, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Copied to " + backup);
}
}By default, copying fails if the target already exists. REPLACE_EXISTING allows the target to be overwritten. This option is useful for backups that should always reflect the latest source, but overwriting is destructive, so choose it deliberately.
Files.copy can copy an empty directory, but it does not recursively copy the directory's contents. To copy a directory tree, walk the source tree and create corresponding directories and files.
Moving and renaming
Files.move changes a file's location. Moving a file within the same directory with a different name is also a rename.
Path oldName = Path.of("draft.txt");
Path newName = Path.of("final.txt");
Files.move(oldName, newName, StandardCopyOption.REPLACE_EXISTING);A move can fail when the destination is on another file system or when the operating system does not support the requested operation. ATOMIC_MOVE requests an atomic move, meaning observers should see either the old name or the new name, not an intermediate state:
Files.move(oldName, newName, StandardCopyOption.ATOMIC_MOVE);The file system may reject this request with AtomicMoveNotSupportedException. Use it when atomic behavior matters, and decide how your application should handle unsupported file systems.
Deleting files and directories
Files.delete(path) removes a file or an empty directory. It throws an exception if the path does not exist or if a directory still contains entries. Files.deleteIfExists(path) performs the same deletion but returns false instead of failing when the path is absent.
Path temporary = Path.of("temporary.txt");
if (Files.deleteIfExists(temporary)) {
System.out.println("Deleted " + temporary);
} else {
System.out.println("Nothing to delete");
}To delete a non-empty directory, first walk its contents and delete entries before deleting the directory itself. Take care with symbolic links: deleting a link removes the link, not the file it points to.
Exercise
Which operation should you use when the original file must remain and an existing destination should be replaced?
Show answer
Use Files.copy with StandardCopyOption.REPLACE_EXISTING.