Get a File Extension in Kotlin with File.extension
In Kotlin, use the extension property of java.io.File to get the part of a file name after its last period. The property returns a String. If the name has no extension, it returns an empty string.
val extension: String = File("file.txt").extension
File.extension examines the file name. The file does not have to exist for Kotlin to return the extension.
Kotlin File.extension Return Values
| File name | Returned extension | Explanation |
|---|---|---|
file.txt | txt | Text after the last period |
archive.tar.gz | gz | Only the final extension is returned |
README | Empty string | The name contains no period |
report. | Empty string | Nothing follows the final period |
.gitignore | gitignore | A leading period is treated as the separator |
PHOTO.JPG | JPG | The original letter case is preserved |
Kotlin Examples for Getting File Extensions
1. Get the Extension of One File
In this example, we will take a file and get its extension.
Main.kt
import java.io.File
fun main(args: Array<String>) {
var f = File("file.txt")
print(f.extension)
}
Make sure file.txt is in the project root directory.
Output
txt
The same result is returned even if file.txt does not exist, because the extension is obtained from the file name rather than the file contents.
2. Get File Extensions of All Entries in a Folder
In this example, we will walk through all the files in the project root directory (if you are running the program from IDE) or all the files in the directory from which you are running the Kotlin program in command line, and print the extension of each file.
Also, we are checking if the current File object is a file using File.isFile() method.
Main.kt
import java.io.File
fun main(args: Array<String>) {
val fileName = "data.txt"
var file = File(fileName)
File("./").walk().forEach {
println(it.extension + " is the extension of " + it.name)
}
}
Output
name is the extension of .name
xml is the extension of codeStyleConfig.xml
xml is the extension of kotlinc.xml
xml is the extension of KotlinJavaRuntime.xml
xml is the extension of misc.xml
xml is the extension of modules.xml
xml is the extension of workspace.xml
txt is the extension of file.txt
iml is the extension of Kotlin Basics.iml
jar is the extension of kotlin-reflect-sources.jar
jar is the extension of kotlin-reflect.jar
jar is the extension of kotlin-stdlib-jdk7-sources.jar
jar is the extension of kotlin-stdlib-jdk7.jar
jar is the extension of kotlin-stdlib-jdk8-sources.jar
jar is the extension of kotlin-stdlib-jdk8.jar
jar is the extension of kotlin-stdlib-sources.jar
jar is the extension of kotlin-stdlib.jar
jar is the extension of kotlin-test-sources.jar
jar is the extension of kotlin-test.jar
class is the extension of HelloWorldKt.class
class is the extension of KotlinExampleKt.class
class is the extension of KotlinForLoopKt.class
class is the extension of KotlinMainKt.class
class is the extension of KotlinStringLengthKt.class
class is the extension of KotlinStringToIntegerKt.class
kotlin_module is the extension of Kotlin Basics.kotlin_module
kt is the extension of HelloWorld.kt
kt is the extension of KotlinExample.kt
kt is the extension of KotlinForLoop.kt
kt is the extension of KotlinMain.kt
kt is the extension of KotlinStringLengthKt.kt
kt is the extension of KotlinStringToIntegerKt.kt
The walk operation visits both files and directories. Because extension works on names, a directory whose name contains a period can also produce a value. Filter the sequence with isFile when only regular files should be included.
3. Print Extensions for Files Only
The following version filters out directories and skips files that have no extension:
import java.io.File
fun main() {
File("./").walk()
.filter { it.isFile }
.filter { it.extension.isNotEmpty() }
.forEach { file ->
println("${file.name}: ${file.extension}")
}
}
Use walkTopDown() instead of walk() when you want to make the traversal direction explicit. Both operations recursively visit subdirectories.
4. Check a File Extension Without Case Sensitivity
The extension retains its original capitalization. Use equals() with ignoreCase = true when names such as photo.jpg and photo.JPG should be treated alike.
import java.io.File
fun main() {
val file = File("PHOTO.JPG")
if (file.extension.equals("jpg", ignoreCase = true)) {
println("The file is a JPEG image.")
}
}
5. Get a Compound Extension Such as tar.gz
For archive.tar.gz, File.extension returns only gz. If your application recognizes compound extensions, check the complete file name.
import java.io.File
fun main() {
val file = File("archive.tar.gz")
val compoundExtension = when {
file.name.endsWith(".tar.gz", ignoreCase = true) -> "tar.gz"
else -> file.extension
}
println(compoundExtension)
}
Output
tar.gz
Get a File Extension from a Kotlin String
If you only have a file-name string and do not need a File object, use substringAfterLast(). Supply an empty string as the missing-delimiter value so that names without a period do not return the complete name.
fun fileExtension(fileName: String): String {
return fileName.substringAfterLast('.', missingDelimiterValue = "")
}
fun main() {
println(fileExtension("document.pdf"))
println(fileExtension("README"))
}
For paths supplied as strings, constructing a File and reading File.extension is usually clearer because it operates on the final name component.
Get a File Extension from an Android Content URI
An Android document selected through the system file picker may be represented by a content:// URI rather than a normal filesystem path. Do not pass the URI string directly to File. Query its display name through ContentResolver, and then extract the extension from that name.
import android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
fun ContentResolver.getFileExtension(uri: Uri): String {
val displayName = query(
uri,
arrayOf(OpenableColumns.DISPLAY_NAME),
null,
null,
null
)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (nameIndex >= 0 && cursor.moveToFirst()) {
cursor.getString(nameIndex)
} else {
null
}
}
return displayName?.substringAfterLast('.', "").orEmpty()
}
When validating an uploaded Android document, also consider checking its MIME type with ContentResolver.getType(uri). A file extension is part of a name and does not guarantee the file’s actual format.
Kotlin File Extension Edge Cases
- Files without a period:
READMEproduces an empty string. - Names ending in a period:
report.also produces an empty string. - Dotfiles:
.gitignoreproducesgitignore, so handle leading-period names separately if your application treats them as extensionless. - Multiple periods:
backup.sql.gzproducesgz. - Uppercase extensions:
IMAGE.PNGproducesPNG; normalize or compare without case when necessary. - Directories containing periods: the property can return an extension for a directory name, so use
isFilewhen processing directory contents. - Untrusted files: an extension alone does not verify a file’s contents or MIME type.
File.extension and Kotlin Extension Functions
The term file extension means the suffix in a name such as txt in notes.txt. A Kotlin extension function is a separate language feature that lets you add callable functionality to a type without modifying that type. File.extension is an extension property supplied by Kotlin’s standard library.
Kotlin Source File Extensions: .kt and .kts
Kotlin source code is normally stored in .kt files. The .kts extension is used for Kotlin script files, including Kotlin-based build scripts such as build.gradle.kts. These source-file suffixes are separate from the File.extension property used to inspect any file name.
Kotlin File Extension FAQs
How do I get a file extension in Kotlin?
Create a java.io.File and read its extension property, as in File("notes.txt").extension. This expression returns txt.
What does File.extension return when there is no extension?
It returns an empty string. You can check this condition with file.extension.isEmpty() or skip such entries with filter { it.extension.isNotEmpty() }.
Does Kotlin File.extension return tar.gz?
No. For archive.tar.gz, it returns gz, which is the text after the final period. Detect tar.gz from the complete name when your program needs compound-extension support.
Can File.extension be used with an Android content URI?
Not directly. Query the URI’s display name with ContentResolver and OpenableColumns.DISPLAY_NAME, or use its MIME type when the actual document type matters.
What is the difference between .kt and .kts?
.kt is the usual extension for Kotlin source files, while .kts identifies Kotlin scripts. A common example of a Kotlin script is build.gradle.kts.
Kotlin File Extension Review Checklist
- Confirm that examples distinguish file names from Android
content://URIs. - Verify that directory traversal filters with
isFilewhen only files are intended. - Test names without extensions, names ending in a period, dotfiles, and names containing multiple periods.
- Use case-insensitive comparisons when uppercase and lowercase extensions should be equivalent.
- Do not treat a file-name extension as proof of the file’s actual content type.
Summary of File Extension Handling in Kotlin
In this Kotlin Tutorial, we learned how to get the extension for a file, or for all files in a folder, using File.extension.
Use File.extension for filesystem names, filter directory walks with isFile, and account for empty, uppercase, dotfile, and compound-extension cases. For an Android content URI, obtain the display name or MIME type through ContentResolver instead of treating the URI as a filesystem path.
TutorialKart.com