【问题标题】:Java to get a list of folders which contains also at least one fileJava获取包含至少一个文件的文件夹列表
【发布时间】:2020-09-10 13:19:34
【问题描述】:

有一个目录结构,我需要从中列出所有文件夹,其中至少包含一个文件。所以当一个文件夹只包含子文件夹时,它不应该被列出。 我尝试为此使用以下代码,但输出中存在空文件夹。

Files.walk(Paths.get("C://testfolderstruct")).filter(Files::isDirectory).filter(Files::exists).forEach(System.out::println);

文件夹结构:

C:.
└───T1
    ├───T2
    └───T3
            test.txt

预期输出:

C:\_privat\teszt\T1\T3

【问题讨论】:

  • Files::exists 真的在这里做你想做的事吗?我的意思是,由 Files.walk() 生成的流中的所有内容都存在,不是吗?在我看来,您需要像 Files::directoryNotEmpty 这样的谓词,但我认为没有。

标签: java nio directory-structure


【解决方案1】:

Files.exists() 只检查给定路径是否存在,但不检查它是否包含文件。您必须获取路径中的文件列表。试试这样的:

public static void main(String[] args) throws IOException {
    Files.walk(Paths.get("C://testfolderstruct"))
        .filter(Files::isDirectory)
        .filter(p -> checkIfEmpty(p))
        .forEach(System.out::println);
}

private static boolean checkIfEmpty(Path directory) {
    try {
        return Files.list(directory)
                .filter(p -> !Files.isDirectory(p))
                .findAny()
                .isPresent();
    }
    catch (IOException e) {
        return false;
    }
}

【讨论】:

  • 我明白了,但它只是列出了所有目录。
  • 如果你使用这个 checkIfEmpty 方法,只会打印有内容的目录。请检查您的文件夹并确保它们确实是空的。
  • 我刚刚再次创建了那个小示例结构。我没有得到预期的输出。
  • 啊,您也不想显示除文件夹外不包含任何内容的任何文件夹。我更新了 checkIfEmpty() 中作为目录的代码和过滤器文件。
【解决方案2】:

对于 递归 空目录:(a/ 只有b/c/d/

    Path path = Paths.get("C:\\...");

    List<Path> paths = new ArrayList<>();
    Files.walkFileTree(path, new SimpleFileVisitor<>() {
        Stack<Integer> filledStack = new Stack<>();

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
            filledStack.push(paths.size());
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                throws IOException {
            int atDir = filledStack.pop();
            if (paths.size() > atDir) {
                paths.add(atDir, dir); // Insert in front.
            }
            return super.postVisitDirectory(dir, exc);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            paths.add(file);
            return super.visitFile(file, attrs);
        }
    });
    paths.forEach(System.out::println);

只需收集常规文件路径并在 postVisitDirectory 上检查是否添加目录。

【讨论】:

    【解决方案3】:

    还有这个使用NIO files.find:

    try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE, (path, attr) -> !attr.isDirectory())) {
            stream.map(Path::getParent).distinct().forEach(System.out::println);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 2021-07-05
      • 2019-05-12
      • 2013-12-25
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      相关资源
      最近更新 更多