Move all files from one directory to another in Java
This post will discuss how to move all files from one directory to another in Java.
1. Using FileUtils.moveDirectory()
method
For copying or moving a directory to another location, you can use third-party libraries like Apache Commons IO whose FileUtils class offers several file manipulation utilities.
The following solution uses the FileUtils.copyDirectory()
method to copy a whole directory to a new location. This method is hugely overloaded to preserve the file dates, apply a filter on a directory, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { File src = new File("/home/data/src"); File dest = new File("/home/data/dest"); try { FileUtils.copyDirectory(src, dest); } catch (IOException e) { e.printStackTrace(); } } } |
2. Using FileUtils.moveDirectory()
method
The copyDirectory()
method only copies the directory. To moves a directory, you can use the FileUtils.moveDirectory()
method (or FileUtils.moveDirectoryToDirectory()
method). You can use it as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { File src = new File("/home/data/src"); File dest = new File("/home/data/dest"); try { FileUtils.moveDirectory(src, dest); } catch (IOException e) { e.printStackTrace(); } } } |
3. Using FileSystemUtils.copyRecursively()
method
The Spring Framework provides various utility methods for working with the file system. You can use the FileSystemUtils.copyRecursively()
method to recursively copy the contents of the source directory to the destination directory. It is overloaded to accept both java.io.File
and java.nio.file.Path
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.springframework.util.FileSystemUtils; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { File src = new File("/home/data/src"); File dest = new File("/home/data/dest"); try { FileSystemUtils.copyRecursively(src, dest); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about moving all files from one directory to another in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)