In this tutorial, you shall learn how to delete a file in Kotlin identified by a given path, using File.delete() function, with example programs.

Kotlin – Delete a File

To delete a file in Kotlin, you can use delete() function of java.io.File class.

Steps to delete a file

  1. Consider that we are given a file identified by a path.
  2. Create a file object from the given file path, and call delete() function on the file object. The function returns true if the file is deleted successfully, or false otherwise.
</>
Copy
val file = File("path/to/file")
file.delete()

Example

Consider that we have a file named info.txt.

In the following program, we shall delete this file by calling delete() function on the file object.

Main.kt

</>
Copy
import java.io.File

fun main() {
    val file = File("info.txt")
    if (file.delete()) {
        println("File deleted successfully.")
    } else {
        println("Error in deleting file.")
    }
}

Output

File deleted successfully.

Now that the file is deleted, let us rerun the above program.

Output

Error in deleting file.

Since the file is already deleted, and now there is no file to delete, File.delete() returns false.

When File.delete() returns false, we can check on more conditions as to why we cannot delete the file, like in the following program.

Main.kt

</>
Copy
import java.io.File

fun main() {
    val file = File("info.txt")
    if (file.delete()) {
        println("File deleted successfully.")
    } else {
        println("Error in deleting file.")
        if (!file.exists()) {
            println("File does not exist.")
        }
    }
}

Output

Error in deleting file.
File does not exist.

Reference tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to delete a file using java.io.File.delete() function.