我正在尝试使用Groovy递归列出所有匹配特定文件类型的文件。这个示例几乎可以实现。但它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,是否有其他方法可以做到这一点?
import static groovy.io.FileType.FILES
new File('.').eachFileRecurse(FILES) {
if(it.name.endsWith('.groovy')) {
println it
}
}
eachFileRecurse
接受一个枚举类型 FileType,用于指定你只对文件感兴趣。问题的其余部分通过过滤文件名轻松解决。值得一提的是,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
}
// Define closure
def result
findTxtFileClos = {
it.eachDir(findTxtFileClos);
it.eachFileMatch(~/.*.txt/) {file ->
result += "${file.absolutePath}\n"
}
}
// Apply closure
findTxtFileClos(new File("."))
println result
将eachDirRecurse
替换为eachFileRecurse
,它就能正常工作。