Kotlin program to delete all files in a folder

Introduction :

In Kotlin, you don’t have to iterate through all files in a folder and delete the files one by one. Kotlin comes with an inbuilt File method called deleteRecursively that can be used to delete all files in a folder. In this post, I will show you how to use deleteRecursively with an example.

Definition :

deleteRecursively is defined in File class. It is defined as like below :

fun File.deleteRecursively(): Boolean

It deletes this caller file with all its children. It is not failsafe i.e. if the operation failed, all previous deleted files can’t be recovered.

It returns one boolean value. true if the deletion is successfull. Else false.

Example :

In the below example, we are deleting one folder with all of its content.

Create one kotlin file and in the same folder, create one new folder sample with a couple of files. Next, copy-paste the below code in that file and run it :

import java.io.File

fun main() {
    val file = File("sample")
    file.deleteRecursively()
}

It will delete the folder sample and all of its contents.

Remember to import java.io.File.

Similar tutorials :