我正在尝试递归列出与 Groovy 中特定文件类型匹配的所有文件。这个例子几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有不同的方法吗?
问问题
66090 次
4 回答
102
这应该可以解决您的问题:
import static groovy.io.FileType.FILES
new File('.').eachFileRecurse(FILES) {
if(it.name.endsWith('.groovy')) {
println it
}
}
eachFileRecurse
接受一个枚举 FileType,它指定您只对文件感兴趣。剩下的问题很容易通过过滤文件名来解决。可能值得一提的是,eachFileRecurse
通常在文件和文件夹上递归,而eachDirRecurse
只找到文件夹。
于 2010-09-08T07:37:02.497 回答
22
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
}
于 2016-08-11T14:42:29.437 回答
6
// Define closure
def result
findTxtFileClos = {
it.eachDir(findTxtFileClos);
it.eachFileMatch(~/.*.txt/) {file ->
result += "${file.absolutePath}\n"
}
}
// Apply closure
findTxtFileClos(new File("."))
println result
于 2010-09-08T02:43:13.810 回答
4
替换eachDirRecurse
为eachFileRecurse
它应该可以工作。
于 2010-09-07T20:09:43.403 回答