Java – Recursively lists all files in a given directory, except for files in hidden folders

Recursively lists all files in a given directory, except for files in hidden folders… here is a solution to the problem.

Recursively lists all files in a given directory, except for files in hidden folders

I have the following code:

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

This returns a list of file names with relative paths within the given path.
I’m somehow stuck in additoinally excluding all files placed somewhere in the file structure in a hidden folder. Any suggestions?

Solution

You can use Files.walkFileTree instead of 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 long, but it’s just as efficient as Files.find.

(If you’re wondering why DosFileAttributes is specifically handled there, it’s because documentation for Files.isHidden states, “On Windows, if the file is not a directory and the DOS Hidden attribute is set.” ”)

Related Problems and Solutions