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

问题描述 投票:36回答:4

我试图递归列出与Groovy中的特定文件类型匹配的所有文件。 This example几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有不同的方法吗?

recursion groovy matching
4个回答
81
投票

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

import static groovy.io.FileType.FILES

new File('.').eachFileRecurse(FILES) {
    if(it.name.endsWith('.groovy')) {
        println it
    }
}

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


14
投票

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
}

4
投票

eachDirRecurseand替换eachFileRecurse它应该工作。


4
投票
// Define closure
def result

findTxtFileClos = {

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

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

println result
© www.soinside.com 2019 - 2024. All rights reserved.