Mark Estrada
Mark Estrada

Reputation: 9201

Exclude File Filter

I used the following code to filter files that are having the following extension

FileFilter fileFilter= new WildcardFileFilter("*.docx");
File[] sampleFiles= filesDirectory.listFiles(fileFilter);

But what if I want the opposite, I want to exclude files that are having this extension. Currently I have the following code

public class FileFilter {
    public static void main(String[] args) {
        File dir = new File("C:\\temp\\filter-exclude");

        File[] files = dir.listFiles(new ExcludeFilter());
        for (File f : files) {
            System.out.println("file: " + f.getName());
        }
    }

    public static class ExcludeFilter implements java.io.FileFilter {

        @Override
        public boolean accept(File file) {
            if (file.getName().toLowerCase().endsWith("docx")) {
                return false;
            }
            return true;
        }

    }
}

But not sure if there are classes already for this. Is there such a class?

Upvotes: 2

Views: 2932

Answers (4)

akourt
akourt

Reputation: 5563

Is there any specific reason you're not using the nio package and instead use the old io?

By using the nio package you can get your code to shrink considerably. Also you'll be using what is the best tools to operate with file and the filesystem in general. Have a look at the snippet below:

var matcher = FileSystems.getDefault().getPathMatcher("*.docx");
try {
    DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:\\temp"), entry -> !matcher.matches(entry));
    stream.forEach(path -> System.out.println("file: " + path.getFileName()));
} catch (IOException e) {
    e.printStackTrace();
}

Effectively this does what your code does, using nothing but the out of the box API provided by the nio package to list directories and filter files based on their suffix.

Upvotes: 0

Thilo
Thilo

Reputation: 262734

You could compose with the notFileFilter:

dir.listFiles(
 FileFilterUtils.notFileFilter(
   FileFilterUtils.suffixFileFilter(".docx")))

Upvotes: 5

Thomas K.
Thomas K.

Reputation: 6770

As you're using commons-io already, have a look at NotFileFilter.

Given your use-case, an example looks like that:

FileFilter fileFilter = new NotFileFilter(new WildcardFileFilter("*.docx"))
File[] files = dir.listFiles(fileFilter);

Upvotes: 2

davidxxx
davidxxx

Reputation: 131466

There is not built-in FileFilter implementations that handle common cases such as yours.
To shorter you could use an anonymous class or better a lambda as FileFilter is a functional interface such as :

 File[] files = dir.listFiles(f -> !f.getName().toLowerCase().endsWith("docx"));

Upvotes: 3

Related Questions