views:

35

answers:

3

I am trying to recursively list all files that match a particular file type in Groovy. The example at link text

almost does it. However, it does not list the files in the root folder. Is there a way to modify this to list files in the root folder? Or, is there a different way to do it?

TIA

+1  A: 

replace eachDirRecurse by eachFileRecurseand it should work.

Riduidel
A: 
// Define closure
def result

findTxtFileClos = {

        it.eachDir(findTxtFileClos);
        it.eachFileMatch(~/.*.txt/) {file ->
                result += "${file.absolutePath}\n"
        }
    }

// Apply closure
findTxtFileClos(new File("."))

println result
Aaron Saunders
Your snippet will find the same file several times. To make it work you will have to use eachDirRecurse instead and for each dir use dir.eachFileMatch to find the files in the directory. Check my solution for another way to solve the problem.
xlson
new approach...
Aaron Saunders
+2  A: 

This should solve your problem:

import static groovy.io.FileType.FILES

new File('.').eachFileRecurse(FILES) {
    if(it.name.endsWith('.groovy')) {
        println it
    }
}

eachFileRecurse takes an enum FileType that specifies that you are only interested in files. The rest of the problem is easily solved by filtering on the name of the file. Might be worth mentioning that eachFileRecurse normally recurses over both files and folders while eachDirRecurse only finds folders.

xlson