Groovy - Delete File
Deleting Files in Groovy
To delete a file in Groovy, you can use the File.delete() method. This method deletes the files or directory from the given path.
Syntax
Following is the syntax of deleting a file using File.delete() method −
File file = new File("hello.txt");
if(file.exists()){
file.delete();
}
Example - Deleting File from Current Directory
Following is the example to demonstrate File.delete() method usage to delete an existing file in current directory−
Example.groovy
class Example {
static void main(String[] args) throws IOException {
new File('test.txt').withWriter('utf-8') {
writer -> writer.writeLine 'Hello World'
}
File file = new File("test.txt");
if(file.exists()) {
boolean success = file.delete();
if (success) {
println("The file has been successfully deleted.");
}else {
println("The file deletion failed.");
}
}else {
println("The file is not present.");
}
}
}
Output
The above code would create file test.txt write a text to it and then delete the same using File.delete() method.
This will produce the following result −
The file has been successfully deleted.
Example - Deleting File That Does Not Exist
Following is the example to demonstrate File.delete() method call to delete an non-existing file in current directory. As file is not present, it returns false as result.
Example.groovy
class Example {
static void main(String args[]) throws IOException {
File file = new File("test1.txt");
boolean success = file.delete();
if (success) {
println("The file has been successfully deleted.");
}else {
println("The file deletion failed.");
}
}
}
Output
The above code would try to delete test1.txt which is not present in current directory. As file is not present, file.delete() method returns false.
This will produce the following result −
The file deletion failed.
Example - Deleting All Files From Given Directory
Following is the example to demonstrate File.delete() method usage to delete all files in given directory recursively.
Example.groovy
class Example {
static void deleteFiles(File dirPath) {
File[] filesList = dirPath.listFiles();
for(File file : filesList) {
if(file.isFile()) {
file.delete();
} else {
deleteFiles(file);
}
}
}
static void main(String[] args) throws IOException {
//Creating a File object for directory
File file = new File("D:\\test");
//List of all files and directories
deleteFiles(file);
println("Files deleted.");
}
}
Output
The above code first create a file object for a directory and then delete all files lying in the folder.
This will produce the following result −
Files deleted.