Kotlin – Delete Recursively

To delete a file/folder and its children in Kotlin, use extension function to java.io.File, File.deleteRecursively().

Syntax

The syntax of File.deleteRecursively() method is

fun File.deleteRecursively(): Boolean (source)

This function returns true if the operation is successful, else false.

Any error during the operation could result in partial deletion of the files in the given directory.

ADVERTISEMENT

Example 1 – Delete Files Recursively in Folder

In the following example, we delete all the files and folders present in “folderA” and also delete the “folderA” itself, recursively, using File.deleteRecursively() method.

example.kt

import java.io.File

fun main(args: Array<String>) {
    var fileA = File("folderA")
    fileA.deleteRecursively()
}

folderA

Kotlin Delete Recursively

When you run this program, all files and folders inside and including folderA shall be deleted.

Conclusion

In this Kotlin Tutorial, we learned to delete a folder and its children recursively, using File.deleteRecursively() method.