0

I use this code to get all the files from a given directory recursively.

List<File> fileList = (List<File>) FileUtils.listFiles(new File(directoryName), null , true);

I would like to exclude some files from listing, so second parameter value of method isn't suitable for this purpose. I tried to use also notFileFilter, but I can't use it recursively.

FileFilter fileFilter1 =   FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".info", null));
List<File> fileList = (List<File>) FileUtils.listFiles(new File(directoryName), fileFilter1, true);
plaidshirt
  • 5,189
  • 19
  • 91
  • 181
  • Does this answer your question? [Exclude specific sub-directories using apache commons fileutils](https://stackoverflow.com/questions/20658841/exclude-specific-sub-directories-using-apache-commons-fileutils). For sure, you should adapt it. – Giancarlo Romeo Apr 22 '20 at 14:00
  • 1
    @GiancarloRomeo : I edited question. – plaidshirt Apr 22 '20 at 14:06
  • 1
    You can find a nice solution here too: https://stackoverflow.com/questions/2056221/recursively-list-files-in-java – Giancarlo Romeo Apr 22 '20 at 14:24

2 Answers2

1

For Java 8 and above you can do it with easily stream api

List<File> filteredList = fileList.stream().filter(f -> f.getName().endsWith(".some_extension")).collect(Collectors.toList());
Amin Rezaei
  • 376
  • 2
  • 11
1

Use the other overload of the listFiles method:

FileFilter notInfoFilter = FileFilterUtils.notFileFilter(
        FileFilterUtils.suffixFileFilter(".info", IOCase.SYSTEM));

Collection<File> files = FileUtils.listFiles(
        new File(directoryName), notInfoFilter, TrueFileFilter.INSTANCE);
Andreas
  • 154,647
  • 11
  • 152
  • 247