在给定目录中递归列出所有文件,但不包括隐藏文件夹中的文件。

3
我有以下代码片段:

我有以下代码片段:

Files.find( startPath, Integer.MAX_VALUE, ( path, attributes ) -> path.toFile().isFile() )
            .map( p -> startPath.relativize( p ).toString() ).collect( Collectors.toList() );

这将返回给定路径内相对路径下的文件名列表。我在额外排除所有放置在文件结构中某个隐藏文件夹中的文件方面遇到了困难。有什么建议吗?


你可以过滤流来检查文件是否被隐藏? - Andrii Abramov
@AndriiAbramov 这个不起作用,因为它只会忽略隐藏文件,我想要忽略的是在隐藏目录中的文件。 - Moonlit
2个回答

3

你可以使用Files.walkFileTree代替Files.find:

List<String> files = new ArrayList<>();

Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file,
                                     BasicFileAttributes attr)
    throws IOException {
        if (attr.isRegularFile()) {
            files.add(startPath.relativize(file).toString());
        }
        return super.visitFile(file, attr);
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir,
                                             BasicFileAttributes attr)
    throws IOException {
        if (Files.isHidden(dir) ||
            (attr instanceof DosFileAttributes && 
                ((DosFileAttributes) attr).isHidden())) {

            return FileVisitResult.SKIP_SUBTREE;
        }
        return super.preVisitDirectory(dir, attr);
    }
});

这段代码看起来更长,但与 Files.find 相比并不少效率。

(如果你想知道为什么要特别处理 DosFileAttributes,那是因为 Files.isHidden 的文档 中指出:“在 Windows 上,一个文件被认为是隐藏的,当且仅当它不是目录且 DOS hidden 属性被设置。”)


0
尝试以下方法:
替换
Files.find( startPath, Integer.MAX_VALUE, ( path, attributes ) -> path.toFile().isFile() )
            .map( p -> startPath.relativize( p ).toString() ).collect( Collectors.toList() );

使用

Files.find( startPath, Integer.MAX_VALUE, ( path, attributes ) -> path.toFile().isFile() ).filter(e -> !e.toFile().isHidden())
            .map( p -> startPath.relativize( p ).toString() ).collect( Collectors.toList() );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接