You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@groovy.apache.org by Merlin Beedell <MB...@cryoserver.com> on 2021/01/26 17:37:46 UTC

Delete empty folders in a tree

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