In this tutorial, you shall learn how to check if a given file is writable in Kotlin, using File.canWrite() function, with example programs.
Kotlin – Check if file is writable
To check if given file is writable in Kotlin, we can use canWrite() function from the java.io.File class.
Steps to check if file is writable
- Consider that we are given a file identified by a path.
- Create a file object from the given path to file. Call canWrite() function on the file object. The function returns true if the file is writable, or false if the file is not writable.
val file = File("path/to/file")
file.canWrite()
Examples
1. Check if file “info.txt” is writable
In the following program, we check if the text file: info.txt
is writable.
From the permissions information, you can observe that the file has read and write access for all users.
Main.kt
import java.io.File
fun main() {
val file = File("info.txt")
if (file.canWrite()) {
println("$file is writable")
} else {
println("$file is not writable")
}
}
Output
info.txt is writable
2. Check if file “secret.txt” is writable
In the following program, we check if the text file: secret.txt
is writable.
From the permissions information, you can observe that the file has write access only to root user. And the user from which we are running the program is different.
Main.kt
import java.io.File
fun main() {
val file = File("secret.txt")
if (file.canWrite()) {
println("$file is writable")
} else {
println("$file is not writable")
}
}
Output
secret.txt is not writable
The file is not writable for the user.
Conclusion
In this Kotlin Tutorial, we learned how to check if file is writable using java.io.File.canWrite() function.