Check Whether a File Exists in Kotlin
To check whether a file exists in Kotlin, create a java.io.File object and call its exists() method. It returns true when a file-system entry exists at the specified path and false when no entry is found.
val exists: Boolean = File("data.txt").exists()
The entry can be a regular file or a directory. If the program specifically requires a regular file, combine exists() with isFile.
Check a File with Kotlin File.exists()
In the following example, the program checks whether data.txt exists. Because this is a relative path, Kotlin resolves it from the application’s current working directory.
Main.kt
import java.io.File
fun main(args: Array<String>) {
val fileName = "data.txt"
var file = File(fileName)
var fileExists = file.exists()
if(fileExists){
print("$fileName exists.")
} else {
print("$fileName does not exist.")
}
}
Output
data.txt exists.
This output assumes that data.txt is present in the working directory. If it is absent, the program prints data.txt does not exist.
Check Whether the Kotlin Path Is a File or Directory
exists() alone does not distinguish a regular file from a directory. Use isFile when the path must identify a file and isDirectory when it must identify a directory.
import java.io.File
fun main() {
val path = File("data.txt")
when {
path.isFile -> println("The path identifies a file.")
path.isDirectory -> println("The path identifies a directory.")
else -> println("The path does not exist.")
}
}
The isFile and isDirectory properties return false when the path does not exist. They can therefore be used directly when the required entry type is already known.
Check an Absolute File Path in Kotlin
An absolute path identifies a location independently of the working directory. The following example also prints the resolved path, which can help diagnose an unexpected false result.
import java.io.File
fun main() {
val file = File("/home/user/documents/data.txt")
println("Path: ${file.absolutePath}")
println("Exists: ${file.exists()}")
}
Replace the example path with a valid path for the operating system on which the program runs. Avoid hard-coded machine-specific paths when the application must run on different systems.
Check File Existence with Kotlin Path.exists()
Programs that use Java NIO paths can use Kotlin’s kotlin.io.path.exists extension. It provides a direct existence check for a Path.
import kotlin.io.path.Path
import kotlin.io.path.exists
fun main() {
val path = Path("data.txt")
if (path.exists()) {
println("$path exists.")
} else {
println("$path does not exist.")
}
}
By default, the existence check follows symbolic links. Pass LinkOption.NOFOLLOW_LINKS when the program must test the link itself instead of its target.
import java.nio.file.LinkOption
import kotlin.io.path.Path
import kotlin.io.path.exists
fun main() {
val path = Path("data-link.txt")
val entryExists = path.exists(LinkOption.NOFOLLOW_LINKS)
println("File-system entry exists: $entryExists")
}
Check a File Before Reading It in Kotlin
If a program intends to read a regular file, checking isFile is more precise than checking only exists(). The read operation can still fail because the file may be removed, permissions may change, or another file-system error may occur after the check.
import java.io.File
import java.io.IOException
fun main() {
val file = File("data.txt")
if (!file.isFile) {
println("A readable data file was not found.")
return
}
try {
val content = file.readText()
println(content)
} catch (exception: IOException) {
println("The file could not be read: ${exception.message}")
}
}
An existence check should not replace error handling around the operation that uses the file. Between the check and the operation, the state of the file system can change.
Check Whether a File Exists in Kotlin for Android
For a file stored in an Android app-specific directory, construct the File from an Android Context location such as filesDir, and then call exists().
val file = File(filesDir, "data.txt")
if (file.exists()) {
println("The internal app file exists.")
} else {
println("The internal app file does not exist.")
}
An Android Uri is not always a direct file-system path. For a content URI returned by the Storage Access Framework or another content provider, use ContentResolver to access it rather than converting the URI to File.
val canOpenUri = try {
contentResolver.openInputStream(uri)?.use { true } ?: false
} catch (exception: Exception) {
false
}
Whether a content URI remains accessible also depends on its provider and the permissions granted to the application.
Why File.exists() May Return False in Kotlin
- The relative path is being resolved from a different working directory than expected.
- The filename, extension, or letter case does not match the actual entry.
- A parent directory in the path is incorrect or missing.
- The application does not have sufficient access to determine whether the entry exists.
- The file was moved or deleted before the check ran.
- On Android, a content URI was incorrectly treated as a direct file path.
Print file.absolutePath when debugging a relative path. This shows the exact location checked by the program.
Kotlin File Existence FAQs
Does File.exists() check both files and directories in Kotlin?
Yes. It returns true when any file-system entry exists at the path. Use isFile or isDirectory when the entry type matters.
How do I check whether a Kotlin file does not exist?
Negate the result with !file.exists(). For a NIO Path, Kotlin also provides notExists(), although an inaccessible path may be neither conclusively known to exist nor known not to exist.
Does File.exists() create the file in Kotlin?
No. exists() only checks the path. Use createNewFile(), writeText(), or another file-writing method when the file must be created.
Should I call File.exists() before every Kotlin file operation?
No. A separate check is useful when it changes the program’s behavior, but the file can change immediately afterward. Always handle errors from the actual read, write, move, or delete operation.
Can File.exists() check an Android content URI?
Not reliably. A content:// URI may not represent a direct file path. Use Android’s ContentResolver and the permission associated with the URI.
Kotlin File Existence QA Checklist
- Confirm whether the path should identify a regular file, a directory, or either type.
- Verify the resolved absolute path when the Kotlin code uses a relative filename.
- Check filename spelling, extension, and case against the actual file-system entry.
- Handle failures from the operation performed after the existence check.
- For Android, distinguish app-specific
Filepaths from provider-backedcontentURIs.
Summary of Checking File Existence in Kotlin
In this Kotlin Tutorial, we learned how to check whether a file exists using File.exists() and Path.exists(). We also distinguished files from directories, checked absolute and relative paths, handled symbolic links, and covered app-specific files and content URIs on Android.
TutorialKart.com