Java:将包含文件和目录的目录移动到新路径

lea*_*ner 11 java unix file

我有一个包含一些文件的目录和包含更多文件的子目录.

Folder -  Directory (path -> /home/abc/xyz/Folder)
  ->Abc.txt  (file)
  -> Xyz.zip (file)
  -> Address (Sub Directory)
         -> PWZ.log (file)
         -> CyZ.xml (file)
  -> DataLog.7zip
Run Code Online (Sandbox Code Playgroud)

等等

我想要做的是将这个完整的目录从一个路径移动到另一个路径,包括所有文件和子文件夹(及其文件).

即将此"文件夹"从/ home/abc/xyz/Folder移至/ home/abc/subdir/Folder.

Java是否提供任何基于FOLDER目录执行此任务的API,或者我们是否需要将每个文件递归复制到此路径?

Man*_*ani 10

您只需使用即可移动目录

import static java.nio.file.StandardCopyOption.*;

Files.move(new File("C:\\projects\\test").toPath(), new File("C:\\projects\\dirTest").toPath(), StandardCopyOption.REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

更改源和目​​标路径

请参阅此处以获取更多详细信息

另请注意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
Run Code Online (Sandbox Code Playgroud)

如果您尝试在同一分区中移动文件,上面的代码就足够了(即使它有条目也可以移动目录).如果不是(而不是移动)你需要使用递归作为其他答案提到.


Doo*_*opy 8

如果您已经导入了Apache Commons

FileUtils.moveDirectory(oldDir, newDir);
Run Code Online (Sandbox Code Playgroud)

请注意,newDir必须事先不存在。从javadocs:

public static void moveDirectory(File srcDir,
                                 File destDir)
                      throws IOException
Run Code Online (Sandbox Code Playgroud)

移动目录。当目标目录在另一个文件系统上时,执行“复制和删除”。

参数:
srcDir - 要移动的目录
destDir - 目标目录

抛出:
NullPointerException - 如果源或目标为 null
FileExistsException - 如果目标目录存在
IOException - 如果源或目标无效
IOException - 如果移动文件时发生 IO 错误


Rus*_*ser 7

Files.move()只要文件系统能够"移动"文件,它就会工作.这通常要求您移动到同一磁盘上的其他位置.


flo*_*oon 6

最好的方法可能是递归方法,例如:这是我为将文件移动到临时文件夹而创建的方法。

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;
}
Run Code Online (Sandbox Code Playgroud)