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 call 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.12.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
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.
Hi Akshoy,
To copy a directory and all its contents you can use the
FileUtils.copyDirectory()
method. Check the following example: Copy directory contents.Hi, great post, how to move all files from directory excluding directory child? I have a folder with images and one sub folder.