O'Reilly logo

Groovy 2 Cookbook by Luciano Fiandesio, Andrey Adamovich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required