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?

有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top