How to copy or move a file
Short answer
Suppose there is a file photo.jpg. Files.copy() copies it, Files.move() moves or renames it:
void main() throws IOException {
Files.copy(Path.of("photo.jpg"), Path.of("photo-backup.jpg"));
Files.move(Path.of("photo.jpg"), Path.of("holiday.jpg"));
IO.println(Files.exists(Path.of("photo.jpg")));
IO.println(Files.exists(Path.of("photo-backup.jpg")));
IO.println(Files.exists(Path.of("holiday.jpg")));
}Output:
false
true
trueOverwriting an existing file
By default copying onto an existing file throws. The REPLACE_EXISTING option allows overwriting:
void main() throws IOException {
Files.writeString(Path.of("backup.jpg"), "old");
Files.copy(Path.of("photo.jpg"), Path.of("backup.jpg"), StandardCopyOption.REPLACE_EXISTING);
IO.print(Files.readString(Path.of("backup.jpg")));
}Output:
image dataInto another folder
resolve() appends a file name to a folder path:
void main() throws IOException {
Path source = Path.of("photo.jpg");
Path archive = Files.createDirectories(Path.of("archive"));
Path target = Files.move(source, archive.resolve(source.getFileName()));
IO.println(target.toString().replace('\\', '/'));
}Output:
archive/photo.jpgCommon mistake
Copying without the option when the target file already exists:
void main() throws IOException {
Files.writeString(Path.of("backup.jpg"), "old");
Files.copy(Path.of("photo.jpg"), Path.of("backup.jpg"));
}Output:
Exception in thread "main" java.nio.file.FileAlreadyExistsException: backup.jpgFunctions used in this recipe
- Path.of() — Creates a Path object — a path to a file or folder.