Java:使用nio Files.copy移动目录

Ada*_*m_G 9 java nio file

我是nio类的新手,无法将文件目录移动到新创建的目录中.

我首先创建2个目录:

File sourceDir = new File(sourceDirStr); //this directory already exists
File destDir = new File(destDirectoryStr); //this is a new directory
Run Code Online (Sandbox Code Playgroud)

然后我尝试将现有文件复制到新目录中,使用:

Path destPath = destDir.toPath();
for (int i = 0; i < sourceSize; i++) {
    Path sourcePath = sourceDir.listFiles()[i].toPath();
    Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
Run Code Online (Sandbox Code Playgroud)

这会引发以下错误:

Exception in thread "main" java.nio.file.FileSystemException: destDir/Experiment.log: Not a directory
Run Code Online (Sandbox Code Playgroud)

我知道这destDir/Experiment.log不是现有的目录; 它应该是一个新的文件作为Files.copy操作的结果.有人可以指出我的操作出错了吗?谢谢!

Aar*_*and 15

您需要使用walkFileTree来复制目录.如果在目录上使用Files.copy,则只会创建一个空目录.

以下代码取自/改编自http://codingjunkie.net/java-7-copy-move/

File src = new File("c:\\temp\\srctest");
File dest = new File("c:\\temp\\desttest");
Path srcPath = src.toPath();
Path destPath = dest.toPath();

Files.walkFileTree(srcPath, new CopyDirVisitor(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING));

public static class CopyDirVisitor extends SimpleFileVisitor<Path>
{
    private final Path fromPath;
    private final Path toPath;
    private final CopyOption copyOption;

    public CopyDirVisitor(Path fromPath, Path toPath, CopyOption copyOption)
    {
        this.fromPath = fromPath;
        this.toPath = toPath;
        this.copyOption = copyOption;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
    {
        Path targetPath = toPath.resolve(fromPath.relativize(dir));
        if( !Files.exists(targetPath) )
        {
            Files.createDirectory(targetPath);
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption);
        return FileVisitResult.CONTINUE;
    }
}
Run Code Online (Sandbox Code Playgroud)


Rud*_*Est 5

如果目标目录不存在,只需创建目标目录即可。

File sourceDir = new File(source); //this directory already exists
File destDir = new File(dest); //this is a new directory
destDir.mkdirs(); // make sure that the dest directory exists

Path destPath = destDir.toPath();
for (File sourceFile : sourceDir.listFiles()) {
    Path sourcePath = sourceFile.toPath();
    Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
Run Code Online (Sandbox Code Playgroud)

请注意,sourceDir.listFiles()还将返回目录,您要么想要递归到该目录,要么忽略...