This post will discuss how to delete a file in Kotlin.

1. Using File.delete() function

A simple solution to delete a given file in Kotlin is using the File.delete() function, which returns true if the file is deleted successfully. No exception is thrown in case the file doesn’t exist or an I/O error occurs, only false is returned on failure. This function clearly lacks error insight, and it is challenging to diagnose why a file cannot be deleted.

Download Code

2. Using Files.deleteIfExists() function

A better solution to delete a file if it exists is using the static Files.deleteIfExists() function. It returns true if the file was deleted by the function, and false if it doesn’t exist. In case of an I/O error, java.io.IOException is thrown.

Download Code

 
If you want the function to throw an IOException if a file doesn’t exist, use the Files.delete() function instead.

Download Code

That’s all about deleting a file in Kotlin.