Java:使用nio Files.copy移动目录 [英] Java: Using nio Files.copy to Move Directory

查看:2056
本文介绍了Java:使用nio Files.copy移动目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to the nio class, and am having trouble moving a directory of files to a newly created directory.

我首先创建2个目录:

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

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

I then try to copy the existing files into the new directory, using:

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 操作,它应该是一个新文件。有人可以指出我的操作出错了吗?谢谢!

I know that destDir/Experiment.log is not an existing directory; it should be a new file as a result of the Files.copy operation. Could someone point out where my operation is going wrong? Thanks!

推荐答案

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

You need to use walkFileTree to copy directories. If you use Files.copy on a directory only an empty directory will be created.

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

Following code taken/adapted from 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;
    }
}

这篇关于Java:使用nio Files.copy移动目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆