Searching for files
In this recipe, we will show how easy it is to filter out files and folders during a search operation on the file system.
Getting ready
Let's assume that we are searching for files in a current working directory. For that, we need to define a variable of the java.io.File
type that points to the .
path:
def currentDir = new File('.')
How to do it...
As we already mentioned in the Walking through a directory recursively recipe, Groovy adds a powerful traverse
method for helping us with our searching task. Let's explore the options that are given by that method:
The simplest way to search for specific files is to apply some filtering logic within a closure that we pass to the
traverse
method:currentDir.traverse { File file -> if (file.name.endsWith('.groovy')) { println file.name } }
The
traverse
method has another overloaded version that accepts aMap
of the parameters. One of those parameters isnameFilter
, which should be of thejava.util.regex.Pattern
type. So, our...