You can copy a file or directory using thecopyTomethod. The copy fails if the target file exists, unless theREPLACE_EXISTINGopton 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_LINKSorREPLACE_EXISTINGoptions.This method takes a varargs argument — the following
StandardCopyOptionandLinkOptionenums 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 theFileAlreadyExistsExceptionexception.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-timeis 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
copyTomethod 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
Copyexample usescopyToand theFiles.walkFileTreemethod to support a recursive copy. See Walking the File Tree for more information.