johnny johnny - 20 days ago 5
Java Question

recursively display all files with certain extension

i was given some psuedocode to get me going but I can't figure it all out. the extension is assigned to the variable "ext"

If f.isFile() is true, then
If f.getPath() ends with the extension, then
Add f.getPath() to the foundFiles array list
Return // this is the end of recursion
Else // This must be a directory
For each subFile in f.listFiles() // This gets all the files in the directory
Call findMatchingFiles(subFile) // This is the recursive call


this is what I have so far and can't seem to fill in the blanks. any tips or help is greatly appreciated.

public void findMatchingFiles(File f) {

if (f.isFile() == true) {
if () {

foundFiles.add(f.getPath());
}

return;
} else {
for ( : ) {
findMatchingFiles(subFile);
}

}

}
}

Answer
public void findMatchingFiles(File f) {

    //i added this. you need to change it to be whatever extension you want to match
    String myExtension = ".exe";

    if (f.isFile() == true) {

        //i added this block. it gets the extension and checks if it matches
        int i = fileName.lastIndexOf('.');
        String extension = fileName.substring(i+1);
        if (extension.equals(myExtension)) {
            foundFiles.add(f.getPath());
        }
        return;
    } else {

        //i added this. it gets all the files in a folder
        for (File subFile : f.listFiles()) {
            findMatchingFiles(subFile);
        }
    }
}

The code above should solve your problem. The two things you were missing were:

  1. How to get the files in a folder. A google search found this: Getting the filenames of all files in a folder
  2. How to get the file extension. A google search found this: How do I get the file extension of a file in Java?

I plugged those both into your code and it should work fine. Also note the variable I added named myExtension. You will need to change this variable to reflect whatever extension you actually want to match.

Comments