java - 使用 Java 7 仅访问特定深度的目录

标签 java nio directory-walk

使用方法时

java.nio.file.Files.walkFileTree(Path root, Set options, int maxDepth, FileVisitor visitor)

可以指定要访问的文件的最大深度。还有一种方法可以指定只访问特定的、精确深度的路径吗?

更具体地说,我只想访问目录,但这可以轻松检查

if (attrs.isDirectory()) {
    // do something
}

visitFile回调。


示例:假设我有一个包含文件 root/dir1/dir11/file.a 的目录结构和root/dir2/file.b我打电话walkFileTreerootmaxDepth=2 。然后,我只想处理

root/dir1/dir11

我不想处理文件root/dir2/file.b ,其深度也为 2,其他目录路径的深度也小于 2:

root
root/dir1
root/dir2

最佳答案

有趣的是,这个简单的实现正是我想要的:

Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), 2, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
        if (attrs.isDirectory()) {
            process(path);
        }
        return FileVisitResult.CONTINUE;
    }
});

也就是说,对于给定的示例,它只会处理 root/dir1/dir11

该解决方案利用明显矛盾的方法来过滤访问文件中的目录。然而,walkFileTree 的 JavaDoc 解释了为什么会产生所需的行为:

For each file encountered this method attempts to read its java.nio.file.attribute.BasicFileAttributes. If the file is not a directory then the visitFile method is invoked with the file attributes. (...)

The maxDepth parameter is the maximum number of levels of directories to visit. (...) The visitFile method is invoked for all files, including directories, encountered at maxDepth (...)

关于java - 使用 Java 7 仅访问特定深度的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026294/

相关文章:

java - Netty大POJO传输错误: TooLongFrameException

scala - 使用 Scala 2.8 continuations 递归遍历一个 LARGE 目录

java - Hibernate查询机

java - Spring 应用程序不考虑 spring.schemas

java - 运行时在 jar 中添加文件

c - 将 Java NIO Files.walkFileTree 访问者移植到 C,维护线程安全

c - 使用 chdir() 而不是绝对路径进行目录遍历

java - 如何求出随机输入的数字的最小、最大、平均值、总和?

Java java.nio 写入 []s 行

java - 为什么缓冲区还没有写入FileChannel