简体   繁体   中英

How to get a return value from a recursive Groovy closure?

i seem to have written a recursive closure :) difficult enough but i am not struggling on how to get feedback from this closure. My written closure deletes a file recursively from the a starting point on the filesystem. I want to now how many files have been deleted!

How can is get feedback on how many files i have deleted? I tried with delegate etc but no luck so far..

  def deleteClosure deleteClosure = { it.eachDir( deleteClosure ) it.eachFileMatch( ~".*123.jpg" ) { it.delete() } } 
    deleteClosure(new File("/tmp/delete.me"))

There is no need to write your own recursive closure code, Groovy adds an eachFileRecurse method to File objects. To get a count of files deleted you can always just increment a counter:

import groovy.io.*

def filesDeletedCount = 0
new File('/tmp/delete.me').eachFileRecurse(FileType.FILES) {
    if (it.name ==~ /.*123.jpg$/) {
        it.delete()
        filesDeletedCount++
    }
}

println "Files deleted: ${filesDeletedCount}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM