You can copy a file or directory using thecopyTo
method. The copy fails if the target file exists, unless theREPLACE_EXISTING
opton 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
orREPLACE_EXISTING
options.This method takes a varargs argument — the following
StandardCopyOption
andLinkOption
enums are supported:
REPLACE_EXISTING
— Performs the copy even when the target file already exists. If the target is a symbolic link, the link itself is copied (and not the target of the link). If the target is a non-empty directory, the copy fails with theFileAlreadyExistsException
exception.COPY_ATTRIBUTES
— Copies the file attributes associated with the file to the target. The exact file attributes supported are file system and platform dependent, butlast-modified-time
is supported across platforms and is copied to the target file.NOFOLLOW_LINKS
— Indicates that symbolic links should not be followed. If the file to be copied is a symbolic link, the link is copied (and not the target of the link).The
copyTo
method is simple to use: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 usescopyTo
and theFiles.walkFileTree
method to support a recursive copy. See Walking the File Tree for more information.