当前位置: 首页 > 面试题库 >

Java: Using nio Files.copy to Move Directory

范修伟
2023-03-14
问题内容

我是nio类的新手,在将文件目录移动
到新创建的目录时遇到麻烦。

我首先用2创建目录:

File sourceDir = new File(sourceDirStr); //this directory already exists
File destDir = new File(destDirectoryStr); //this is a new directory

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

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

这将引发以下错误:

Exception in thread "main" java.nio.file.FileSystemException: destDir/Experiment.log: Not a directory

我知道这destDir/Experiment.log不是现有目录;由于该Files.copy操作,它应该是一个新文件。有人可以指出
我的操作出了什么问题吗?谢谢!


问题答案:

您需要使用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;
    }
}


 类似资料:

相关阅读

相关文章

相关问答