I have one directory containing some files and sub directory having more files in it.
Folder - Directory (path -> /home/abc/xyz/Folder)
->Abc.txt (file)
-> Xyz.zip (file)
-> Address (Sub Directory)
-> PWZ.log (file)
-> CyZ.xml (file)
-> DataLog.7zip
etc
What I am trying to do is move this complete Directory from one path to another including all the files and subfolder(and their files).
ie Move this "Folder" from /home/abc/xyz/Folder to /home/abc/subdir/Folder.
Does Java provides any API to do this task based on FOLDER directory or do we need to do recursive copy each and every file only to this path?
You can move a file or folder from one folder to another by dragging it from its current location and dropping it into the destination folder, just as you would with a file on your desktop. Folder Tree: Right-click the file or folder you want, and from the menu that displays click Move or Copy.
You can simply move directory by using
import static java.nio.file.StandardCopyOption.*;
Files.move(new File("C:\\projects\\test").toPath(), new File("C:\\projects\\dirTest").toPath(), StandardCopyOption.REPLACE_EXISTING);
Change source and destination path
Refer here to get more details
Also Note from API
When invoked to move a
* directory that is not empty then the directory is moved if it does not
* require moving the entries in the directory. For example, renaming a
* directory on the same {@link FileStore} will usually not require moving
* the entries in the directory. When moving a directory requires that its
* entries be moved then this method fails (by throwing an {@code
* IOException}). To move a <i>file tree</i> may involve copying rather
* than moving directories and this can be done using the {@link
* #copy copy} method in conjunction with the {@link
* #walkFileTree Files.walkFileTree} utility method
If you try to move the file in the same partition , the above code is sufficient ( it can move directory even it has entries). if not ( instead of move) you need to use recursive as other answer mentioned.
private static void move(File sourceFile, File destFile) {
if (sourceFile.isDirectory()) {
File[] files = sourceFile.listFiles();
assert files != null;
for (File file : files) move(file, new File(destFile, file.getName()));
if (!sourceFile.delete()) throw new RuntimeException();
} else {
if (!destFile.getParentFile().exists())
if (!destFile.getParentFile().mkdirs()) throw new RuntimeException();
if (!sourceFile.renameTo(destFile)) throw new RuntimeException();
}
}
works for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With