Groovy(文件IO):查找所有文件并返回所有文件-Groovy方式 [英] Groovy (File IO): find all files and return all files - the Groovy way
问题描述
好,这应该很容易...
Ok, this should be easy...
我是groovy的新手,我希望实现以下逻辑:
I'm new to groovy and I'm looking to implement the following logic:
def testFiles = findAllTestFiles();
到目前为止,我想出了下面的代码,该代码可以成功打印所有文件名.但是,除了打印之外,我只需要将它们放入集合中即可.当然,我可以使用旧的Java方法执行此操作:只需实例化一个集合,添加所有元素并返回它.但是,那不会教我任何东西.
So far, I've come up with the code below which successfully prints all files names. However, instead of printing, I just need to put them into a collection. Of course, I could do this the old java way: just instantiate a collection, add all the elements and return it. However, that wouldn't teach me anything.
那么,您如何以一种酷炫的时髦"方式做到这一点?
So how do you do this the cool, "Groovy" way?
static File[] findAllTestFiles() {
def directory = new File("src/test/java");
def closure = {File f -> if(f.name =~ /Test\.java$/) println f }
directory.eachFileRecurse FileType.FILES, closure
return null;
}
我希望在Groovy中使用尽可能少的代码来实现 findAlltestFiles(),同时仍保持可读性.
I'm looking to implement findAlltestFiles() in Groovy using as little code as possible while still being readable.
推荐答案
我会尝试避免完全构建集合.使用闭包,您可以将逻辑从实际想要使用的文件中分离出来,例如:
I'd try to avoid building the collection entirely. Using closures, you can separate the logic to select the files from what you actually want to do with them, like so:
import groovy.io.FileType
def withEachTestFile(Closure closure) {
new File("src/test/java").eachFileRecurse(FileType.FILES) {
if (it.name =~ /Test\.java$/) {
closure.call(it)
}
}
}
然后,如果您想对测试文件进行操作,则可以直接进行操作而无需在内存中建立列表:
Then if you want to do something on the test files, you can do it directly without building up a list in memory:
withEachTestFile() { println it }
或者,如果您真的想要列表,则可以使用有意义的任何集合轻松生成它:
or if you really want the list, you can easily generate it, using whatever collection makes sense:
def files = []
withEachTestFile() { files << it }
这篇关于Groovy(文件IO):查找所有文件并返回所有文件-Groovy方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!