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
<!-- https://search.maven.org/remotecontent?filepath=commons-io/commons-io/2.11.0/commons-io-2.11.0.jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
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.