Question

In the code below:

public File[] findFiles (String path)
{
    FilenameFilter textFilter = new FilenameFilter()
    {
        @override
        public boolean accept(File dir, String name)
        {
            if(name.toLowerCase().endsWith(".txt"))
                return true;
            else
                return false;
        }
    };

    File[] txtFiles = new File(path).listFiles(textFilter);

    return txtFiles;
}

I understand that an anonymous class, which implements the interface FilenameFilter, is defined and instantiated. But I don't understand how the method accept is called without being called directly.

Was it helpful?

Solution

If you check the source code of listFiles, the accept method is being called. here's the source code

public File[] listFiles(FilenameFilter filter) {
String ss[] = list();
if (ss == null) return null;
ArrayList v = new ArrayList();
for (int i = 0 ; i < ss.length ; i++) {
    if ((filter == null) || filter.accept(this, ss[i])) {
                                   ^^^^^^
    v.add(new File(ss[i], this));
    }
}
return (File[])(v.toArray(new File[v.size()]));
}

OTHER TIPS

The accept() method is called within the File.listFiles() method for every File found in the (directory) File it's called on.

This is a callback pattern in action.

An implementation of FilenameFilter requires the accept method to be overridden as you have done so. So when you use listFiles( FilenameFilter filter ), the filter in the listFiles() method calls the accept method whether to accept or not.

This link will help: http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top