Java Reference
In-Depth Information
If the NOFOLLOW_LINKS option is used, the copy() method copies the symbolic link, not the target of the
symbolic link.
Listing 10-5 demonstrates the use of the copy() method to copy a file. It handles the possible exceptions if the
copy operation fails. You will need to change the paths for the source and target files before running the program.
Listing 10-5. Copying a File, a Directory, and a Symbolic Link Using the Files.copy() Method
// CopyTest.java
package com.jdojo.nio2;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.DirectoryNotEmptyException;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
public class CopyTest {
public static void main(String[] args) {
// Change the paths for teh source and target files
// before you run the program
Path source = Paths.get("C:\\poems\\luci1.txt");
Path target = Paths.get("C:\\poems\\luci1_backup.txt");
try {
Path p = Files.copy(source, target,
REPLACE_EXISTING, COPY_ATTRIBUTES);
System.out.println(source + " has been copied to " + p);
}
catch (FileAlreadyExistsException e) {
System.out.println(target+ " already exists.");
}
catch (DirectoryNotEmptyException e) {
System.out.println(target + " is not empty.");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The move(Path source, Path target, CopyOption... options) method of the Files class lets you move or
rename a file. The move operation fails if the specified target file already exists. You can specify the REPLACE_EXISTING
option to replace the existing target file. If the file to move is a symbolic link, it moves the symbolic link, not the target
of the symbolic link. The move() method can only be used to move an empty directory.
A DirectoryNotEmptyException is thrown if the directory is not empty.
 
Search WWH ::




Custom Search