简体   繁体   English

递归列出给定目录中的所有文件,隐藏文件夹中的文件除外

[英]List all files recursively in a given Directory except files in hidden folders

I have the following piece of code:我有以下一段代码:

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

Which will return a List of file names with relative path inside a given path.这将返回给定路径内具有相对路径的文件名列表。 I am somehow stucked at additoinally excluding all the files which are placed in hidden folders somewhere along the file structure.我不知何故坚持要排除所有放置在文件结构某处隐藏文件夹中的文件。 Any suggestions?有什么建议?

You can use Files.walkFileTree instead of Files.find:您可以使用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);
    }
});

The code looks longer, but it's no less efficient than Files.find.代码看起来更长,但效率不亚于 Files.find。

(If you're wondering why the specific handling of DosFileAttributes is in there, it's because the documentation for Files.isHidden states, “On Windows a file is considered hidden if it isn't a directory and the DOS hidden attribute is set.”) (如果您想知道为什么要对 DosFileAttributes 进行特定处理,那是因为Files.isHidden文档指出,“在 Windows 上,如果文件不是目录并且设置了 DOS hidden属性,则该文件被认为是hidden 。” )

Try the following:请尝试以下操作:

Replace代替

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

with

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() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM