我试图递归列出与Groovy中的特定文件类型匹配的所有文件。 This example几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有不同的方法吗?
这应该可以解决您的问题:
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
}
用eachDirRecurse
and替换eachFileRecurse
它应该工作。
// Define closure
def result
findTxtFileClos = {
it.eachDir(findTxtFileClos);
it.eachFileMatch(~/.*.txt/) {file ->
result += "${file.absolutePath}\n"
}
}
// Apply closure
findTxtFileClos(new File("."))
println result