Groovy provides a File.deleteDir() method that deletes a complete tree of 
directories AND files.  But what if I just want to delete empty directories?
It would be useful if this method could take an optional parameter (e.g. 
Boolean  -  onlyEmpty = if true only delete if empty) - or perhaps even a 
closure returning true/false to determine the criteria on which deletion should 
occur - e.g. delete folder and content unless the folder contains a particular 
file.

This simple method below will delete any empty folders below the provided File 
path.  For performance, it is over simple, as it could skip deletes of parent 
folders where a child folder is not empty (hence not deleted).

  void clearEmptyDirectories(File aDir) {
      def emptyDirs = []

      aDir.eachDirRecurse { testDir ->
        emptyDirs << testDir
      }
      // reverse so that we do the deepest folders first
      // but do not delete a folder if it is not empty
      emptyDirs.reverseEach { it.delete() }
  }

Merlin Beedell

Reply via email to