0

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.

Melika Barzegaran
  • 429
  • 2
  • 9
  • 25

3 Answers3

3

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()]));
}
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • Additionally, in your IDE you can attach source code for Java supplied classes and it will help to find out more.. – sanbhat Mar 27 '14 at 08:53
2

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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)

Zyn
  • 614
  • 3
  • 10