Java Quiz Player

Blog Post

Notes on Java File IO (NIO 2) API's Files.move()

Feb 13, 2013

This blog post is about usage of the Java File IO (NIO 2) API's java.nio.file.Files class's move static method.

1. Move or rename a file to a target file.

move(Path source, Path target, CopyOption… options)

Returns: Target file Path.

Parameters: File Path (source and target) and CopyOption.

Copy Options: REPLACE_EXISTING and ATOMIC_MOVE. See details on Copy Options (at the bottom of this blog post).


AccessDeniedException, AtomicMoveNotSupportedException, FileAlreadyExistsException and DirectoryNotEmptyException are defined in java.nio.file package and are subclasses of

1.1. Description

CopyOption →
File type ↓
File Moves a file to target. Moves a file to target. Moves a file to target.
Directory (and its entries are moved) Moves a directory. Moves a directory. Moves a directory.
Symbolic Link (the link itself, not the target of the link, is moved) Moves a link. Moves a link. Moves a link.

NOTE: When the ATOMIC_MOVE copy option is used, the move replaces any existing non-directory target file.

2. Example (for Windows OS):

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FilesMoveExample {
    public static void main (String [] args)
            throws IOException {
        Path srcePath = Paths.get("C:\\java nio2\\testfolder\\folder1");		
        Path targetPath = Paths.get("C:\\java nio2\\testfolder\\folder2");
        targetPath = Files.copy(srcePath, targetPath); // Statement A

2.1. Running

Assume folder1 is a directory and contains a file file1.txt.

Scenario 1: Scenario 2: Scenario 3:

3. Copy Options

The copy() and move() methods of the Files class use the java.nio.file.CopyOption interface. CopyOption configures how to copy or move a file. LinkOption and StandardCopyOption enums implement CopyOption.

3.1. StandardCopyOption enum

Copy attributes to the new file. Minimally, the last-modified-time attribute is copied to the target file. Used only with the copy(Path source, Path target).

Replace an existing file.

Move the file as an atomic file system operation. Used only with the move() method.

3.2. LinkOption enum

Do not follow symbolic links. Used only with the copy(Path source, Path target).

4. References

Java SE 7 API > java.nio.file (NIO 2).

Return to top


Comments are welcome. Please note that comments are moderated.
Email to: info(at)javaquizplayer(dot)com.