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:

  1. 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')) ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.