Question

I want to collect all (sub-)directories within directory matching a given name using Apache IO Commons. While I can solve this task for files using a NameFileFilter in combination with FileUtils.listFiles, I can't find a solution to do 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 the NameFileFilter. What am I doing wrong?

Was it helpful?

Solution

Your code only looks 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top