How to Move a File or Directory In Java?

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

You can move a file or directory in Java using move() method:

                                public static Path move(Path source,
                                                        Path target,
                                                        CopyOption... options)
                                                 throws IOException
                              

It will move or rename a file to a target file. This method moves a file to the target file with the options parameter specifying how the move is performed. According to Java documentation options parameter may include any of the following:

REPLACE_EXISTING
If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
ATOMIC_MOVE
The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException. If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

Here is a simple Java program that shows how to move a file:

JavaMoveFileExample.java

                            package com.tutorial.java.files;

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

                            public class JavaMoveFileExample {

                                public static void main(String[] args) throws IOException {
                                    Path source = Paths.get("/home/dir1/sample.txt");
                                    Path destination = Paths.get("/home/dir2/sample.txt");
                                    Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
                                    System.out.println("File moved!");
                                }
                            }