Deleting a file or directory
Deleting a file or directory may seem a trivial task and it often is, but it has some hidden quirks that Groovy may help you with. This recipe will enlist and give details about several methods to delete a file or a directory.
Getting ready
Let's assume that we have two java.io.File
variables: one pointing to a normal file and another to a nonempty directory with several subdirectories in it. For example:
def dir = new File('./tmp1') def file = new File('./tmp2/test.txt')
As you know from Java, the java.io.File
class has a delete
method and it works perfectly in many situations. But it will only delete a normal file or an empty directory. So, to delete a nonempty directory you need to write a recursive function in Java. Also, in most of the situations, the delete
method will not throw any exceptions; it will just return false if it fails to delete a file or directory.
How to do it...
Let's explore several ways to delete things on the file system.
To delete the nonempty...