Trail: Essential Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)
Copying a File or Directory
Home Page > Essential Classes > Basic I/O
Copying a File or Directory
You can copy a file or directory by using the copyTo method. The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified.

Directories can be copied. However, files inside the directory are not copied, so the new directory is empty even when the original directory contains files.

When copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option.

This method takes a varargs argument. The following StandardCopyOption and LinkOption enums are supported:

If you are not familiar with enums, see Enum Types.

The following shows how to use the copyTo method:

import static java.nio.file.StandardCopyOption.*;
...
try {
    path.copyTo(newPath, REPLACE_EXISTING, COPY_ATTRIBUTES);
} catch (IOException x) {
    //Logic for error condition...
    System.err.println(x);
    return;
}

The Copy example uses the copyTo and Files.walkFileTree methods to support a recursive copy. See Walking the File Tree for more information.

Previous page: Deleting a File or Directory
Next page: Moving a File or Directory