Loading...

Sunday, 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

3 comments:

kémèt aka the baby said...

Wonderful , i have to admit i don't look too much a the goovy api groovy.util for exemple. but yeah that's the kind of things i need for my groovy sysadmin scripting ...

Mike Miller said...

Mr Haki,

I am running 1.6.5 and got an error with the second call. I think it needs to be the following:

def icoFiles = new FileNameByRegexFinder().getFileNames(groovyHome, '/.*\\.ico/')

parms passed on getFileNames() not the constructor and I had to escape the \ inside the regex.

mrhaki said...

@Mike Miller: I had forgotten to use the getFileNames() method like you already suggested. I am running the sample on my Windows computer with Cygwin, but I didn't need to escape the \ character. By using the /../ (slashy) String syntax we don't have to escape special characters. So instead of '/.*\\.ico/', you can use /.*\.ico/ (so without the single quotes around it).

Post a Comment