Files.copy: Basic File Copying
What you'll learn: How to copy files in Java using the Files.copy method with source and target Path objects.
Now that you've mastered reading and writing file contents, there's a simpler way to duplicate entire files: the Files.copy method. Instead of manually reading bytes from one file and writing them to another, Files.copy handles the entire operation for you in a single method call.
How Files.copy Works
The basic syntax is straightforward:
Path source = Paths.get("original.txt");
Path target = Paths.get("copy.txt");
Files.copy(source, target);
This reads the entire source file and writes it to the target path. The method handles buffering and resource management internally—no need for explicit streams or readers.
Default Behavior and Exceptions
By default, Files.copy:
- Creates the target file if it doesn't exist
- Throws
FileAlreadyExistsExceptionif the target already exists (it won't overwrite by default) - Throws
NoSuchFileExceptionif the source file doesn't exist - Throws
IOExceptionfor other I/O problems (permissions, disk space, etc.)
try {
Path source = Paths.get("data.txt");
Path target = Paths.get("backup.txt");
Files.copy(source, target);
System.out.println("File copied successfully");
} catch (FileAlreadyExistsException e) {
System.err.println("Target file already exists");
} catch (IOException e) {
System.err.println("Copy failed: " + e.getMessage());
}
Think of Files.copy as a "smart copy" operation: it protects you from accidentally overwriting existing files unless you explicitly tell it otherwise (though you haven't learned those options yet).
Key Takeaway: Use Files.copy(source, target) to duplicate files safely and efficiently; by default it fails rather than overwriting existing files, throwing FileAlreadyExistsException when the target exists.