Skip to main content

How to recursively delete files and directories in Kotlin

How to recursively delete files and directories in Kotlin.

Here's a detailed step-by-step tutorial on how to recursively delete files and directories in Kotlin:

  1. Import the necessary classes:
import java.io.File
  1. Create a function to delete a file:
fun deleteFile(file: File) {
if (file.isDirectory) {
val files = file.listFiles()
if (files != null) {
for (subFile in files) {
deleteFile(subFile)
}
}
}
file.delete()
}
  1. Create a function to delete a directory:
fun deleteDirectory(directory: File) {
if (directory.isDirectory) {
val files = directory.listFiles()
if (files != null) {
for (subFile in files) {
deleteFile(subFile)
}
}
}
directory.delete()
}
  1. Use the functions to recursively delete files and directories:
val fileToDelete = File("path/to/file.txt")
deleteFile(fileToDelete)

val directoryToDelete = File("path/to/directory")
deleteDirectory(directoryToDelete)

In the above example, we first import the File class from the java.io package. This class represents a file or directory path.

Next, we create a function called deleteFile which takes a File object as a parameter. Inside the function, we check if the given file is a directory. If it is, we get a list of all the files and directories inside it and recursively call the deleteFile function for each of them. Finally, we delete the file.

Similarly, we create a function called deleteDirectory which takes a File object representing a directory. Inside this function, we check if the directory exists and is actually a directory. If it is, we recursively delete all the files and directories inside it using the deleteFile function. Finally, we delete the directory itself.

To use these functions, you simply need to create a File object representing the file or directory you want to delete, and then call the respective function (deleteFile or deleteDirectory). For example, in the code snippet provided, we delete a file named "file.txt" located at "path/to/file.txt", and a directory located at "path/to/directory".

That's it! You have learned how to recursively delete files and directories in Kotlin using the File class and some helper functions.