I would like to get a list of files with a specific extension in a directory. In the API (Java 6), I see a method File.listFiles(FileFilter)
which would do this.
Since I need a specific extension, I created a FileNameExtensionFilter
. However I get a compilation error when I use listFiles
with this. I assumed that since FileNameExtensionFilter implements FileFilter
, I should be able to do this. Code follows:
FileNameExtensionFilter filter = new FileNameExtensionFilter("text only","txt");
String dir = "/users/blah/dirname";
File f[] = (new File(dir)).listFiles(filter);
The last line shows a compilation error:
method listFiles(FileNameFilter) in type File is not applicable for arguments of type FileNameExtensionFilter
I am trying to use listFiles(FileFilter)
, not listFiles(FileNameFilter)
. Why does the compiler not recognize this?
This works if I write my own extension filter extending FileFilter
. I would rather use FileNameExtensionFilter
than write my own. What am I doing wrong?
Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter
Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.
One-liner in java 8 syntax:
With java lambdas (available since java 8) you can simply convert
javax.swing.filechooser.FileFilter
tojava.io.FileFilter
in one line.Here's something I quickly just made and it should perform far better than File.getName().endsWith(".xxxx");
Here's an example for various images formats.
Is there a specific reason you want to use
FileNameExtensionFilter
? I know this works..The
FileNameExtensionFilter
class is intended for Swing to be used in aJFileChooser
.Try using a
FilenameFilter
instead. For example: