Documentation

The Java™ Tutorials
Hide TOC
Copying a File or Directory复制文件或目录
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)

Copying a File or Directory复制文件或目录

You can copy a file or directory by using the copy(Path, Path, CopyOption...) method. 您可以使用copy(Path, Path, CopyOption...)方法复制文件或目录。The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified.如果目标文件存在,则复制失败,除非指定了REPLACE_EXISTING选项。

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.如果要复制链接本身而不是链接的内容,请指定NOFOLLOW_LINKSREPLACE_EXISTING选项。

This method takes a varargs argument. 此方法采用varargs参数。The following StandardCopyOption and LinkOption enums are supported:支持以下StandardCopyOptionLinkOption枚举:

If you are not familiar with enums, see Enum Types.如果不熟悉enums,请参阅枚举类型

The following shows how to use the copy method:下面显示了如何使用copy方法:

import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

In addition to file copy, the Files class also defines methods that may be used to copy between a file and a stream. 除了文件复制之外,Files类还定义了可用于在文件和流之间复制的方法。The copy(InputStream, Path, CopyOptions...) method may be used to copy all bytes from an input stream to a file. copy(InputStream, Path, CopyOptions...)方法可用于将输入流中的所有字节复制到文件中。The copy(Path, OutputStream) method may be used to copy all bytes from a file to an output stream.copy(Path, OutputStream)方法可用于将文件中的所有字节复制到输出流。

The Copy example uses the copy and Files.walkFileTree methods to support a recursive copy. Copy示例使用copyFiles.walkFileTree方法支持递归复制。See Walking the File Tree for more information.有关详细信息,请参阅遍历文件树


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