Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Deleting Directories



Groovy provides File class which represents a directory or File object which provides operations to delete file or directories.

Example - Deleting a File

File.delete() method return true it is able to delete the file. It returns false otherwise.

Example.groovy

// get an empty file
def file = new File('sample.txt')
 
// delete the File
if(file.delete()){
   println "File '${file.name}' deleted."
}else{
   println "Failed to delete file '${file.name}'."
}

// get a non-empty file
file = new File('log.txt')
 
// delete the File
if(file.delete()){
   println "File '${file.name}' deleted."
}else{
   println "Failed to delete file '${file.name}'."
}

Output

When we run the above program, we will get the following result.

File 'sample.txt' deleted.
File 'log.txt' deleted.

Example - Deleting an Empty Directory

File.delete() method return true it is able to delete the directory. It returns false otherwise. In case directory is non-empty, delete() method will not delete it.

Example.groovy

// get an empty directory
def directory = new File('Empty')
 
// delete the empty directory
if(directory.delete()){
   println "Directory '${directory.name}' deleted."
}else{
   println "Failed to delete directory '${directory.name}'."
}

// get a non-empty file
directory = new File('TestDirectory')
 
// delete the empty directory
if(directory.delete()){
   println "Directory '${directory.name}' deleted."
}else{
   println "Failed to delete directory '${directory.name}'."
}

Output

When we run the above program, we will get the following result.

Directory 'Empty' deleted.
Failed to delete directory 'TestDirectory'.

Example - Deleting a non-empty Directory

File.deleteDir() method delete contents of a directory recursively and then delete the directory.

Example.groovy

// get a non-empty file
directory = new File('TestDirectory')
 
// delete the empty directory
if(directory.deleteDir()){
   println "Directory '${directory.name}' deleted."
}else{
   println "Failed to delete directory '${directory.name}'."
}

Output

When we run the above program, we will get the following result.

Directory 'TestDirectory' deleted.
Advertisements