How do you filter the result of the list() method of the File object?

Alessandro A. Garbagnati

Create a new class (there are people that consider this a waste and use anonymous classes) that implements the FilenameFilter.
This is an example for filtering all the XML files in a directory:


public class FilterXMLFile implements FilenameFilter {

     *  you just need to implement the accept method
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
Then, in your code, you can do something like this:
File myDir = new File(<the directory>);
File[] xmlFiles = myDir.listFiles(new FilterXMLFile());
You can do the same thing with a FileFilter.
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact