Monday, January 31, 2022

[SOLVED] Java: Move Directory containing files and directories to new path

Issue

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?


Solution

The best approach is probably a recursive method, like: This is a method I created for moving files into a temp folder.

private boolean move(File sourceFile, File destFile)
{
    if (sourceFile.isDirectory())
    {
        for (File file : sourceFile.listFiles())
        {
            move(file, new File(file.getPath().substring("temp".length()+1)));
        }
    }
    else
    {
        try {
            Files.move(Paths.get(sourceFile.getPath()), Paths.get(destFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}


Answered By - flotothemoon
Answer Checked By - Cary Denson (WPSolving Admin)