Recursive listing of all files matching a certain filetype in Groovy

半腔热情 提交于 2019-11-28 23:39:10

问题


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?


回答1:


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.




回答2:


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
}



回答3:


// Define closure
def result

findTxtFileClos = {

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

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

println result



回答4:


replace eachDirRecurse by eachFileRecurse and it should work.



来源:https://stackoverflow.com/questions/3662144/recursive-listing-of-all-files-matching-a-certain-filetype-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!