Recursion Groovy中与特定文件类型匹配的所有文件的递归列表
我试图递归地列出与Groovy中特定文件类型匹配的所有文件。几乎做到了。但是,它不会列出根文件夹中的文件。是否有办法修改此选项以列出根文件夹中的文件?或者,有不同的方法吗?用Recursion Groovy中与特定文件类型匹配的所有文件的递归列表,recursion,groovy,matching,Recursion,Groovy,Matching,我试图递归地列出与Groovy中特定文件类型匹配的所有文件。几乎做到了。但是,它不会列出根文件夹中的文件。是否有办法修改此选项以列出根文件夹中的文件?或者,有不同的方法吗?用eachFileRecurse替换eachDirRecurse,这样应该可以解决您的问题: // Define closure def result findTxtFileClos = { it.eachDir(findTxtFileClos); it.eachFileMatch(~/.*
eachFileRecurse
替换eachDirRecurse
,这样应该可以解决您的问题:
// Define closure
def result
findTxtFileClos = {
it.eachDir(findTxtFileClos);
it.eachFileMatch(~/.*.txt/) {file ->
result += "${file.absolutePath}\n"
}
}
// Apply closure
findTxtFileClos(new File("."))
println result
import static groovy.io.FileType.FILES
new File('.').eachFileRecurse(FILES) {
if(it.name.endsWith('.groovy')) {
println it
}
}
eachFileRecurse
采用枚举文件类型,指定您只对文件感兴趣。通过过滤文件名,可以轻松解决问题的其余部分。可能值得一提的是,eachFileRecurse
通常在文件和文件夹上递归,而eachDirRecurse
仅查找文件夹。groovy 2.4.7版:
new File(pathToFolder).traverse(type: groovy.io.FileType.FILES) { it ->
println it
}
您还可以添加过滤器,如
new File(parentPath).traverse(type: groovy.io.FileType.FILES, nameFilter: ~/patternRegex/) { it ->
println it
}
您的代码段将多次找到同一文件。要使其正常工作,您必须使用eachDirress,而对于每个dir,您必须使用dir.eachFileMatch来查找目录中的文件。检查我的解决方案,以了解解决问题的另一种方法。