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. ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.