Search

Dark theme | Light theme

November 22, 2009

Groovy Goodness: Finding Files with FileNameFinder

The groovy.util package contains the FileNameFinder and FileNameByRegExFinder classes. We can use the FileNameFinder classe to search recursively for files in a directory with ANT fileset pattern conventions. With the FileNameByRegExFinder we use regular expressions to define the file patterns.

// Suppose we have a environment variable GROOVY_HOME pointing to the Groovy installation dir.
def groovyHome = System.getenv('GROOVY_HOME')

def txtFiles = new FileNameFinder().getFileNames(groovyHome, '**/*.txt' /* includes */, '**/*.doc **/*.pdf' /* excludes */)
assert new File(groovyHome, 'README.txt').absolutePath in txtFiles

def icoFiles = new FileNameByRegexFinder().getFileNames(groovyHome, /.*\.ico/)
assert new File(groovyHome, 'html/groovy-jdk/groovy.ico').absolutePath in icoFiles