-
Notifications
You must be signed in to change notification settings - Fork 4
Java copying file with Files.copy() API
Ramesh Fadatare edited this page Jul 11, 2019
·
1 revision
Java 7 introduced the Files.copy() method, which provides an easy way of copying a file. The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified. Files.copy() takes an optional third copy options argument.
The options parameter may include any of the following:
- REPLACE_EXISTING - if the target file exists, then the target file is replaced if it is not a non-empty directory.
- COPY_ATTRIBUTES - attempts to copy the file attributes associated with this file to the target file.
- ATOMIC_MOVE - moves the file.
- NOFOLLOW_LINKS - symbolic links are not followed.
The first three options are available in StandarCopyOption; the last one in LinkOption.
The example copies a file with Files.copy(). It replaces the destination if it already exists.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class CopyFileJava7 {
public static void main(String[] args) throws IOException {
File source = new File("src/resources/bugs.txt");
File dest = new File("src/resources/bugs2.txt");
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}