I was looking for a way to get all the files ending with .txt in the current directory. I found the answer of how to do this here https://stackoverflow.com/a/5751357/3972558 and it works. Now I am reviewing my own code and I still do not quite understand how this works, and I am trying to learn from that.
File workingDirectory = new File(System.getProperty("user.dir"));
File[] files = workingDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
How is it possible that you declare a method within where you would usually find a parameter input? I probably ask my question in the wrong way because I do not understand why this syntax is correct.
In specific, how is this a correct input of listFiles()
:
new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
}
Update: I now see that indeed you're implementing the accept method for the FileNameFilter
interface. How is it possible though that you implement it after the keyword new
.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html