This post will discuss how to delete files and subdirectories in a directory in Kotlin.

The standard function to delete the specified file or directory in Kotlin is File.delete(). There are several options to “conditionally” delete files and subdirectories within a directory using this function. For instance,

1. To delete only regular files within the root directory, you can do as follows.

Download Code

 
Note that all subdirectories remain untouched. You can replace the for loop with the stdlib operations filterNot{}.forEach{}.

Download Code

 
2. To delete a subdirectory with the File.delete() function, it should be empty. The idea is to recursively delete all files within the subdirectory, before deleting the subdirectory itself. This is demonstrated below:

Download Code

 
3. Alternatively, to delete the main directory as well (and all its contents), use the Files.walk() function.

Download Code

 
If you need to delete “only files” from the directory and all its subdirectories, apply a filter as follows:

Download Code

That’s all about deleting files and subdirectories in a directory in Kotlin.