Dark theme | Light theme

December 10, 2009

Groovy Goodness: Delete Non-empty Directory Recursively with File

Groovy enhances the File class with several methods. One is the deleteDir() method. With this method we can delete a directory with all it's subdirectories and files. So the directory doesn't need to be empty to run this method.

def mainDir = new File('test') 
def subDir = new File(mainDir, 'app')
def file = new File(subDir, 'test.txt')

subDir.mkdirs()  // Create directories.
file << 'sample'  // Create file and add contents.

assert mainDir.exists() && subDir.exists() && file.exists()

def result = mainDir.deleteDir()  // Returns true if all goes well, false otherwise.
assert result
assert !mainDir.exists() && !subDir.exists() && !file.exists()