Java: Move Directory containing files and directories to new path

You can simply move directory by using

import static java.nio.file.StandardCopyOption.*;

Files.move(new File("C:\\projects\\test").toPath(), new File("C:\\projects\\dirTest").toPath(), StandardCopyOption.REPLACE_EXISTING);

Change source and destination path

Refer here to get more details

Also Note from API

 When invoked to move a
     * directory that is not empty then the directory is moved if it does not
     * require moving the entries in the directory.  For example, renaming a
     * directory on the same {@link FileStore} will usually not require moving
     * the entries in the directory. When moving a directory requires that its
     * entries be moved then this method fails (by throwing an {@code
     * IOException}). To move a <i>file tree</i> may involve copying rather
     * than moving directories and this can be done using the {@link
     * #copy copy} method in conjunction with the {@link
     * #walkFileTree Files.walkFileTree} utility method

If you try to move the file in the same partition , the above code is sufficient ( it can move directory even it has entries). if not ( instead of move) you need to use recursive as other answer mentioned.


If you have imported Apache Commons already anyways:

FileUtils.moveDirectory(oldDir, newDir);

Note that newDir must not exist beforehand. From the javadocs:

public static void moveDirectory(File srcDir,
                                 File destDir)
                      throws IOException

Moves a directory. When the destination directory is on another file system, do a "copy and delete".

Parameters:
srcDir - the directory to be moved
destDir - the destination directory

Throws:
NullPointerException - if source or destination is null
FileExistsException - if the destination directory exists
IOException - if source or destination is invalid
IOException - if an IO error occurs moving the file

Tags:

Unix

Java

File