views:

465

answers:

3

Here is the code I have thus far:

import java.io.*;

class JAVAFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".java"));
    }
}

public class tester {
   public static void main(String args[])
   {
        FilenameFilter filter = new JAVAFilter();
        File directory = new File("C:\\1.3\\");
        String filename[] = directory.list(filter);
   }
}

At this point, it'll store a list of all the *.java files from the directory C:\1.3\ in the string array filename. However, i'd like to store a list of all the java files also in subdirectories (preferably with their path within C:\1.3\ specified also. How do I go about doing this? Thanks!

+3  A: 

I'm afraid you can't do it with the list(FilenameFilter) method. You'll have to list all files and directories, and then do the filtering yourself. Something like this:

public List<File> getFiles(File dir, FilenameFilter filter) {
    List<File> ret = new ArrayList<File>();
    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            ret.addAll(getFiles(f, filter));
        } else if (filter.accept(dir, f.getName())) {
            ret.add(f);
        }
    }
    return ret;
}
Michael Myers
+1  A: 

As far as I know, you will have to do this manually (recursively), i.e. you will have to call list(filter) for all sub-directories of C:\1.3\, and so on....

__roland__
+2  A: 

you should look at DirectoryWalker from Apache

LB