Walking through a directory recursively
Hierarchical file systems are the way we store most of our data. Groovy can help to build code that needs to go through a dense forest of directory trees.
In this recipe, we will cover different ways of walking through a directory tree using Groovy I/O awesomeness.
Getting ready
Let's assume that we need to walk through the current working directory. We can define the currentDir
variable of java.io.File
type that points to it:
def currentDir = new File('.')
To test this recipe, you can use either a script file that you launch with the groovy
command or the groovysh
/groovyConsole
prompt.
How to do it...
As you probably know, the java.io.File
class already provides the
list
and listFiles
methods that return a collection of first-level elements (files and directories) in a directory represented by a File
object. Using a recursive function, you can easily traverse the subfolders found in the first-level folders.
However, Groovy already provides more concise methods...