Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using File.listFiles with FileNameExtensionFilter

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?

like image 249
Anu Avatar asked Apr 22 '11 00:04

Anu


1 Answers

The FileNameExtensionFilter class is intended for Swing to be used in a JFileChooser.

Try using a FilenameFilter instead. For example:

File dir = new File("/users/blah/dirname"); File[] files = dir.listFiles(new FilenameFilter() {     public boolean accept(File dir, String name) {         return name.toLowerCase().endsWith(".txt");     } }); 
like image 195
WhiteFang34 Avatar answered Sep 21 '22 07:09

WhiteFang34