Java DelegateFileFilter-class And Method Code Example


Here is an example of how to use the DelegateFileFilter class from the org.apache.commons.io package in Java:

import java.io.File;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.DelegateFileFilter;
import org.apache.commons.io.filefilter.FileFileFilter;

public class DelegateFileFilterExample {
    public static void main(String[] args) {
        // Create a DelegateFileFilter that only accepts directories and files with the .txt extension
        DelegateFileFilter delegateFileFilter = new DelegateFileFilter(DirectoryFileFilter.INSTANCE,
                new TxtFileFilter());

        // Use the filter to list all directories and .txt files in the current directory
        File dir = new File(".");
        File[] files = dir.listFiles(delegateFileFilter);
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

class TxtFileFilter implements java.io.FileFilter {
    public boolean accept(File file) {
        return file.getName().endsWith(".txt");
    }
}

In this example, the DelegateFileFilter is created by passing in DirectoryFileFilter.INSTANCE and an instance of TxtFileFilter as arguments. This means that the filter will only accept directories and files with the ".txt" file extension.

The DelegateFileFilter is then used to list all directories and ".txt" files in the current directory by calling the listFiles() method on a File object representing the current directory, and passing in the delegateFileFilter object as an argument.