Documentation

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

Moving a File or Directory移动文件或目录

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

Empty directories can be moved. 可以移动空目录。If the directory is not empty, the move is allowed when the directory can be moved without moving the contents of that directory. 如果目录不为空,则当可以移动目录而不移动该目录的内容时,允许移动。On UNIX systems, moving a directory within the same partition generally consists of renaming the directory. 在UNIX系统上,在同一分区内移动目录通常包括重命名目录。In that situation, this method works even when the directory contains files.在这种情况下,即使目录中包含文件,此方法也可以工作。

This method takes a varargs argument – the following StandardCopyOption enums are supported:此方法采用varargs参数–支持以下StandardCopyOption枚举:

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

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

Though you can implement the move method on a single directory as shown, the method is most often used with the file tree recursion mechanism. 尽管可以在单个目录上实现move方法,如图所示,但该方法最常用于文件树递归机制。For more information, see Walking the File Tree.有关详细信息,请参阅遍历文件树


Previous page: Copying a File or Directory
Next page: Managing Metadata (File and File Store Attributes)