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).

Throws:

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

1.1. Description

CopyOption →
File type ↓
No option REPLACE_EXISTING ATOMIC_MOVE
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

FilesMoveExample.java (for Windows OS):

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

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 FilesMoveExample.java

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
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_EXISTING
Replace an existing file.

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

3.2. LinkOption enum

NOFOLLOW_LINKS
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

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