【发布时间】:2011-04-09 09:29:02
【问题描述】:
我正在尝试递归地列出与 Groovy 中特定文件类型匹配的所有文件。 This example 几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有其他方法吗?
【问题讨论】:
我正在尝试递归地列出与 Groovy 中特定文件类型匹配的所有文件。 This example 几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有其他方法吗?
【问题讨论】:
将eachDirRecurse 替换为eachFileRecurse,它应该可以工作。
【讨论】:
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
【讨论】:
这应该可以解决您的问题:
import static groovy.io.FileType.FILES
new File('.').eachFileRecurse(FILES) {
if(it.name.endsWith('.groovy')) {
println it
}
}
eachFileRecurse 采用枚举 FileType 指定您只对文件感兴趣。剩下的问题很容易通过过滤文件名来解决。可能值得一提的是,eachFileRecurse 通常会在文件和文件夹上递归,而eachDirRecurse 只查找文件夹。
【讨论】: