This post will discuss how to delete a directory and all entries in it with Kotlin.

1. Using File.deleteRecursively() function

A simple solution to delete a directory with all its subdirectories is using the File.deleteRecursively() function. It returns true if the directory is successfully deleted; false otherwise. The following code demonstrates its usage:

Download Code

2. Using Files.walkFileTree() function

The idea is to walk the file tree using Files.walkFileTree() function, and delete each file using the Files.delete() function. If the file is a subdirectory, delete it after visiting it and deleting all files in it. The following example demonstrates the usage of these functions to delete a directory:

Download Code

3. Using Files.walk() function

Alternately, we can walk the file tree in a depth-first manner using the Files.walk(…) function that returns a Stream of Path objects. The following code demonstrates the working of the Files.walk(…) function with the File.delete() function to recursively delete the root directory and all its subdirectories.

Note that Comparator.reverseOrder() is used to ensure the parent directory is deleted after the child (Since the directory is processed depth-first and File.delete() cannot delete a non-empty directory).

Download Code

4. Using Runtime.exec() function

Another plausible solution is to execute the remove directory command of the underlying environment. This can be done in Kotlin using the Runtime.exec() convenience function.

Download Code

5. Using File.delete() function

Finally, we can write a recursive routine to delete a directory with the File.delete() function. This would translate to a simple code below:

Download Code

That’s all about deleting a directory in Kotlin.