Delete a file in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.File fun main() { val file = File("/sys/data/foo.txt") val result = file.delete() if (result) { println("Deletion succeeded.") } else { println("Deletion failed.") } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths fun main() { val path = Paths.get("/sys/data/foo.txt") try { val result = Files.deleteIfExists(path) if (result) { println("Deletion succeeded.") } else { println("Deletion failed.") } } catch (e: IOException) { println("Deletion failed.") e.printStackTrace() } } |
If you want the function to throw an IOException if a file doesn’t exist, use the Files.delete() function instead.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths fun main() { val path = Paths.get("/sys/data/foo.txt") try { Files.delete(path) println("Deletion succeeded.") } catch (e: IOException) { println("Deletion failed.") e.printStackTrace() } } |
That’s all about deleting a file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)