Library contents

Groovy File.eachFileRecurse

Walk a directory tree and select matching regular files.

A simple example

File.eachFileRecurse

  1. Start with Folder a contains b/c.txt
  2. Do this Visit descendants
  3. Result The walk reaches c.txt
Recursive traversal descends into b before discovering the file inside it.

Syntax

Groovy syntax
folder.eachFileRecurse(type, action)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Find a receipt below the month folder

A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.

From the programint count = 0
Result1
Lesson.groovy
import java.nio.file.Files
import java.nio.file.Path
import groovy.io.FileType

Path base = Files.createTempDirectory("lesson-")
try {
    def month = Files.createDirectory(base.resolve('March'))
    Files.createFile(month.resolve('dues.csv'))
    Files.createFile(base.resolve('notes.txt'))
    int count = 0
    base.toFile().eachFileRecurse(FileType.FILES) { f ->
        if (f.name.endsWith('.csv')) count++
    }
    println count
} finally {
    base.toFile().deleteDir()
}
Output
1

The month folder contributes one matching receipt below the top level.

Advertisements

Inventory class submissions

A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.

Givenanna.pdf · li.pdf · team/plan.pdf
Worked result3

Inventory rehearsal parts

A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.

Givenscore.pdf · parts/alto.pdf · parts/bass.pdf
Worked result3

What to watch for

Following symbolic links during recursion can revisit directories. Choose link handling deliberately.

Documentation for File.eachFileRecurse