List of directories with a given name recursively with Java

I want to collect all the (sub) directories in the directory corresponding to the name using Apache IO Commons. Although I can solve this problem for files using NameFileFilterin combination with FileUtils.listFiles, I can not find a solution for this for folders.

I tried the following snippet:

IOFileFilter fileFilter = new NameFileFilter(fileName);
Collection<File> fileList = FileUtils.listFilesAndDirs(rootFolder, fileFilter, TrueFileFilter.INSTANCE);

It identifies folders and subfolders, but does not filter them according to NameFileFilter. What am I doing wrong?

+4
source share
1 answer

Your code is looking for files with this name, not for any directories.

This should work:

IOFileFilter nameFilter = new NameFileFilter(fileName);
Collection<File> fileList = FileUtils.listFilesAndDirs(rootFolder, 
  new NotFileFilter(TrueFileFilter.INSTANCE),
  nameFilter);
+3
source

Source: https://habr.com/ru/post/1523341/


All Articles