plaidshirt
plaidshirt

Reputation: 5681

FileUtils.listFiles to exclude specific file extensions from listing

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);

Upvotes: 0

Views: 1698

Answers (2)

Andreas
Andreas

Reputation: 159155

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);

Upvotes: 1

Amin Rezaei
Amin Rezaei

Reputation: 376

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());

Upvotes: 1

Related Questions