Kotlin – Delete File
Deleting a file in Kotlin can be performed using the delete() method of the File
class from the java.io
package. This method deletes the file or directory denoted by the File object.
In this tutorial, we’ll show you how to delete a file in Kotlin, with an example.
Steps to Delete a File in Kotlin
Here is how you can delete a file in Kotlin:
- Import the
File
class from thejava.io
package. - Specify the file path of the file you want to delete.
- Create a
File
object using the file path. - Use the
delete()
method to attempt to delete the file. This method returnstrue
if the file was successfully deleted, andfalse
otherwise. - Include proper error handling to ensure the program can handle any issues that arise during the file deletion process.
Kotlin Example Program to Delete a File
Below is an example of how to delete a file named 'example.txt'
.
Main.kt
import java.io.File
fun main() {
val filePath = "example.txt" // Replace with the path to your file
val file = File(filePath)
val result = file.delete()
if (result) {
println("File deleted successfully.")
} else {
println("Error occurred while deleting the file or file does not exist.")
}
}
Output
File deleted successfully.
The output will confirm whether the file was successfully deleted or if an error occurred.
Summary
In this Kotlin File Operations tutorial, we have learned how to delete a file using the delete()
method of the File
class from the java.io
package. We went through the process step-by-step and provided a practical example for clarity.