开发者

Recursive listing of all files matching a certain filetype in Groovy

开发者 https://www.devze.com 2023-01-15 18:36 出处:网络
I am trying to recursively list all files that match a particular file type in Groovy. This example almost does it. However, it does not list the files in the root folder. Is there a way to modify thi

I am trying to recursively list all files that match a particular file type in Groovy. This example 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?


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.


groovy version 2.4.7 :

new File(pathToFolder).traverse(type: groovy.io.FileType.FILES) { it ->
    println it
}

you can also add filter like

new File(parentPath).traverse(type: groovy.io.FileType.FILES, nameFilter: ~/patternRegex/) { it ->
    println it
}


// Define closure
def result

findTxtFileClos = {

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

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

println result


replace eachDirRecurse by eachFileRecurse and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消