【问题标题】:Moving not empty directory recursively using Java NIO.2 FileVisitor and Files.walkFileTree(...)使用 Java NIO.2 FileVisitor 和 Files.walkFileTree(...) 递归移动非空目录
【发布时间】:2016-05-01 09:20:36
【问题描述】:

我看到了很多关于如何使用 Java NIO.2 递归地复制或删除文件的示例。例如,这是复制文件夹及其所有内容的方法:

/**
 * Copies a folder with all contents recursively. Class implements
 * {@code FileVisitor} interface.
 * @author Ernestas Gruodis
 */
public static class TreeCopy implements FileVisitor<Path> {

        private final Path source;
        private final Path target;
        private final boolean replace;
        private final CopyOption[] options;
        private final ArrayList<Object[]> events = new ArrayList<>();

        /**
         * Copies a folder with all contents recursively.
         *
         * @param source source file path.
         * @param target target file path.
         * @param replace {@code true} if existing file should be replaced.
         */
        public TreeCopy(Path source, Path target, boolean replace) {
            this.source = source;
            this.target = target;
            this.replace = replace;

            options = replace ? new CopyOption[]{COPY_ATTRIBUTES, REPLACE_EXISTING} : new CopyOption[0];
        }

        @Override
        public synchronized FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {

            Path newDir = target.resolve(source.relativize(dir));
            try {
                Files.copy(dir, newDir, options);
            } catch (FileAlreadyExistsException ex) {
                if (!replace) {
                    events.add(new Object[]{"Folder already exists", newDir, ex});
                    return FileVisitResult.TERMINATE;
                } else {
                    return FileVisitResult.CONTINUE;
                }
            } catch (DirectoryNotEmptyException ex) {
                //Ignore
            } catch (IOException ex) {
                events.add(new Object[]{"Unable to create a folder", newDir, ex});
                return FileVisitResult.SKIP_SUBTREE;
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public synchronized FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {

            Path newFile = target.resolve(source.relativize(file));
            try {
                Files.copy(file, newFile, options);
            } catch (FileAlreadyExistsException ex) {
                events.add(new Object[]{"File already exists", newFile, ex});
            } catch (NoSuchFileException ex) {
                events.add(new Object[]{"No such file", newFile.getParent(), ex});
            } catch (IOException ex) {
                events.add(new Object[]{"Unable to create a file", newFile, ex});
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public synchronized FileVisitResult postVisitDirectory(Path dir, IOException exc) {

            if (exc == null) {
                Path newDir = target.resolve(source.relativize(dir));
                try {
                    FileTime time = Files.getLastModifiedTime(dir);
                    Files.setLastModifiedTime(newDir, time);
                } catch (IOException ex) {
                    events.add(new Object[]{"Unable to copy all attributes to", newDir, ex});
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public synchronized FileVisitResult visitFileFailed(Path file, IOException ex) {

            if (ex instanceof FileSystemLoopException) {
                events.add(new Object[]{"Cycle detected", file, ex});
            } else {
                events.add(new Object[]{"Unable to copy", file, ex});
            }
            return FileVisitResult.CONTINUE;
        }

        /**
         * Returns errors which happened while copying a directory.
         *
         * @return {@code ArrayList<Object[]>} error list, where at each entry
         * of {@code Object[]} index:
         * <ul><li> 0 - {@code String} - error description;
         * </li><li> 1 - {@code Path} - target folder/file path;
         * </li><li> 2 - {@code Exception} - specific exception.
         * </li></ul>
         */
        public ArrayList<Object[]> getEvents() {

            return events;
        }
    }


Path source = Paths.get("/toCopyDir"),
    target = Paths.get("/someDir2/etc/toCopyDir");

EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
TreeCopy tc = new TreeCopy(source, target, true);
try {
   Files.walkFileTree(source, opts, Integer.MAX_VALUE, tc);
} catch (IOException ex) {
   //Handle exception
}

但是如何移动包含文件的文件夹呢?有一个方法Files.move(Path source, Path target, CopyOption... options) throws IOException。谁能举个真实有效的例子?

我认为解决方案可能是在preVisitDirectory(...) 中使用Files.copy(...),然后在postVisitDirectory(...) 中使用Files.delete(...),类似这样..

【问题讨论】:

  • Files.move(new File("/path/to/srcFolder").toPath(), new File("/path/to/dstFolder").toPath(), StandardCopyOption.ATOMIC_MOVE) ;为我工作
  • 而且即使目录不为空?
  • 我认为使用FileVisitor可以实现更多的控制。我在preVisitDirectory(...) 中使用Files.copy(...),然后在postVisitDirectory(...) 中使用Files.delete(...)。但仍然不知道是否可以将Files.move(...)FileVisitor 一起使用,可能不会.. 仅用于单个文件和空文件夹。
  • 好的。 windows 7 + jre 8 -> Files.move() 即使目录不为空也可以工作。在 linux + jre 8 上,当 dir 不为空时会引发异常。同样在 windows Files.move() 仅在源文件夹和目标文件夹位于同一文件存储(分区、磁盘、卷...)上时才有效,否则它会引发异常...
  • @guleryuz - 非常有用的信息,谢谢。 Java是跨平台的,所以我认为为了避免错误,Files.walkFileTree(...)加上FileVisitor应该用于移动非空文件夹。

标签: java recursion nio filevisitor simplefilevisitor


【解决方案1】:

这里有一个解决方案:

def moveDir(path: Path, to: Path): Unit = {
Files.createDirectories(to)
Files.walkFileTree(
  path,
  new SimpleFileVisitor[Path] {
    override def preVisitDirectory(
        dir: Path,
        attrs: BasicFileAttributes): FileVisitResult = {
      val targetDir = to.resolve(path.relativize(dir))
      try Files.createDirectory(targetDir)
      catch {
        case e: FileAlreadyExistsException =>
          if (!Files.isDirectory(targetDir)) throw e
      }
      FileVisitResult.CONTINUE
    }

    override def visitFile(file: Path,
                           attrs: BasicFileAttributes): FileVisitResult = {
      Files.move(file, to.resolve(path.relativize(file)))
      FileVisitResult.CONTINUE
    }
  }
)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2010-09-28
    • 2014-04-16
    • 2016-04-25
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多