在Groovy中递归列出与特定文件类型匹配的所有文件

shi*_*mbu 36 recursion groovy matching

我试图递归列出与Groovy中的特定文件类型匹配的所有文件.这个例子差不多了.但是,它不会列出根文件夹中的文件.有没有办法修改它以列出根文件夹中的文件?或者,有不同的方法吗?

xls*_*son 86

这应该可以解决您的问题:

import static groovy.io.FileType.FILES

new File('.').eachFileRecurse(FILES) {
    if(it.name.endsWith('.groovy')) {
        println it
    }
}
Run Code Online (Sandbox Code Playgroud)

eachFileRecurse采用枚举FileType,指定您只对文件感兴趣.通过过滤文件名可以轻松解决问题的其余部分.可能值得一提的是,eachFileRecurse通常eachDirRecurse只对文件和文件夹进行递归,同时只查找文件夹.


Tou*_*umi 16

groovy版本2.4.7:

new File(pathToFolder).traverse(type: groovy.io.FileType.FILES) { it ->
    println it
}
Run Code Online (Sandbox Code Playgroud)

你也可以添加像过滤器一样

new File(parentPath).traverse(type: groovy.io.FileType.FILES, nameFilter: ~/patternRegex/) { it ->
    println it
}
Run Code Online (Sandbox Code Playgroud)


Aar*_*ers 6

// Define closure
def result

findTxtFileClos = {

        it.eachDir(findTxtFileClos);
        it.eachFileMatch(~/.*.txt/) {file ->
                result += "${file.absolutePath}\n"
        }
    }

// Apply closure
findTxtFileClos(new File("."))

println result
Run Code Online (Sandbox Code Playgroud)