Groovy (File IO): find all files and return all files – the Groovy way

filefile-iogroovy

Ok, this should be easy…

I'm new to groovy and I'm looking to implement the following logic:

def testFiles = findAllTestFiles();

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;
}

I'm looking to implement findAlltestFiles() in Groovy using as little code as possible while still being readable.

Best Answer

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 }