You can copy a file or directory by using thecopyTo
method. The copy fails if the target file exists, unless theREPLACE_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
orREPLACE_EXISTING
option.This method takes a varargs argument. The following
StandardCopyOption
andLinkOption
enums are supported:If you are not familiar with
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 file. 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).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 thecopyTo
andFiles.walkFileTree
methods to support a recursive copy. See Walking the File Tree for more information.