learner
learner

Reputation: 1155

Java: Move Directory containing files and directories to new path

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?

Upvotes: 19

Views: 48716

Answers (8)

abdelkarim
abdelkarim

Reputation: 71

public static void move(File srcDir, File destDir) throws IOException {
    FileUtils.copyDirectory(srcDir, destDir, true);
    if(srcDir.isDirectory()) {
        for(File file: srcDir.listFiles()) {
            FileUtils.forceDelete(file);
        }
    }
}

FileUtils from package org.apache.commons.io;

Upvotes: 0

user10262522
user10262522

Reputation: 41

   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

Upvotes: 4

Louis CAD
Louis CAD

Reputation: 11529

You just need to use the renameTo method (already present in the File class from JDK) after you made sure the directories in the destination path are existing (e.g. by calling mkdirs()).

Upvotes: 1

Mani
Mani

Reputation: 3364

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.

Upvotes: 22

AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 36001

Java has this built in, using native OS operation, in File.renameTo(File dest).

Example:

new File("/home/alik/Downloads/src").renameTo(new File("/home/alik/Downloads/target"))

Upvotes: 3

Doopy
Doopy

Reputation: 706

If you have imported Apache Commons already anyways:

FileUtils.moveDirectory(oldDir, newDir);

Note that newDir must not exist beforehand. From the javadocs:

public static void moveDirectory(File srcDir,
                                 File destDir)
                      throws IOException

Moves a directory. When the destination directory is on another file system, do a "copy and delete".

Parameters:
srcDir - the directory to be moved
destDir - the destination directory

Throws:
NullPointerException - if source or destination is null
FileExistsException - if the destination directory exists
IOException - if source or destination is invalid
IOException - if an IO error occurs moving the file

Upvotes: 10

Russell Zahniser
Russell Zahniser

Reputation: 16364

Files.move() will work provided that the file system is able to "move" the file. This usually requires that you be moving to a different location on the same disk.

Upvotes: 8

flotothemoon
flotothemoon

Reputation: 1892

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;
}

Upvotes: 7

Related Questions