Delete subfolders after a given time interval
After a certain time interval(month) I want to delete the subfolders with content. Can someone help me to achieve this. The following code shows errors related to Iterator.
// Create a ref for closure
def dir
def yesterday = ( new Date() ).time - 1000*60*60*24
//de开发者_如何转开发finition Closure
dir = {
while(it.hasNext()){
it.eachDirRecurse( dir )
println("Dir: " + it.canonicalPath)
if(it.lastModified() <= yesterday)
it.deleteDir()
}
}
// Apply closure
dir( new File("H:\\soapUI\\Adres\\") )
This is the Exception:
Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.hasNext() is applicable for argument types: () values: []
Possible solutions: inspect(), getText(), getText(java.lang.String), setText(java.lang.String), setText(java.lang.String, java.lang.String), hashCode()\
at test$_run_closure1.doCall(test.groovy:8)
at test.run(test.groovy:19)
There's at least couple of errors in your code...
- why do you do
it.hasNext()
on a File - you call
it.eachDirRecurse
which will recurse down the whole tree, but you then call it again for every directory in that tree...
You are also going to have problems as you will remove a directory, but then eachDirRecurse
will still try to walk down into that directory and throw a FileNotFoundException
I think you're going to have to not use eachDirRecurse
Assuming you are on Groovy 1.8 (you don't say), you can do something like this:
import groovy.time.TimeCategory
import static groovy.io.FileType.*
def yesterday = use( TimeCategory ) { new Date() - 1.day }
def deleteFoldersIn = { File f ->
f.traverse( [ type:DIRECTORIES, postDir:{ d -> if( d.lastModified() < yesterday.time ) d.deleteDir() } ] ) {
println "Scanning $it"
}
}
// Apply closure
deleteFoldersIn( new File( 'H:\\soapUI\\Adres\\' ) )
Here's the documentation for TimeCategory, FileType and File.traverse()
new File('dir').deleteDir() is recursive for me in groovy 1.8
there's magic in the drink!
Otherwise you can use dir and deleteDir functionality.
DeleteDir: Recursively deletes the current directory and its contents. Symbolic links and junctions will not be followed but will be removed. To delete a specific directory of a workspace wrap the deleteDir step in a dir step.
dir('directoryToDelete') {
deleteDir()
}
精彩评论