How do I move directory to another directory with its entire contents?

Below is an example to move one directory with all its child directory and files to another directory. We can use the FileUtils.moveDirectory() method to simplify the process.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DirectoryMove {
    public static void main(String[] args) {
        String source = "F:/Temp/source";
        File srcDir = new File(source);

        String destination = "F:/Temp/target";
        File destDir = new File(destination);

        try {
            // Move the source directory to the destination directory.
            // The destination directory must not exist prior to the
            // move process.
            FileUtils.moveDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

Wayan

3 Comments

  1. It is deleting source folder and it is asking non-existing folder name. I don’t want to delete my source folder and I want to move folders inside the existing folder. Please help.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.