简体   繁体   English

如何从递归Groovy闭包中获得返回值?

[英]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. 无需编写自己的递归关闭代码,Groovy向File对象添加了eachFileRecurse方法。 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}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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