Trail: Essential Classes
Lesson: Basic I/O
Section: File I/O (featuring NIO.2)
Moving a File or Directory
Home Page > Essential Classes > Basic I/O
Moving a File or Directory
You can move a file or directory using the moveTo method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified.

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, moving a directory within the same partition generally consists of a simple rename — in that situation this method works even when the directory contains files.

This method takes a varargs argument — the following StandardCopyOption enums are supported:

The moveTo method is very simple to use:

import static java.nio.file.StandardCopyOption.*;
...
try {
    path.moveTo(newPath, REPLACE_EXISTING);
} catch (IOException x) {
    // Logic for error condition...
    System.err.println(x);
    return;
}

Though you can implement the moveTo method on a single directory as shown, it is most likely to be used in conjunction with the file tree recursion mechanism. For more information, see Walking the File Tree.

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