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.16.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
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.