Get File Extension in Kotlin
In Kotlin, to extract or get the file extension, use extension property of the java.io.File class. File.extension is a String value. It returns the extension if the file has an extension, or an empty string if the file does not have an extension.
Examples
1. Get File Extension
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
2. Get File Extensions of All Files 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 KotlinStringLength.kt kt is the extension of KotlinStringToInteger.kt
Conclusion
In this Kotlin Tutorial, we learned how to get the extension for a file, or for all files in a folder, using File.extension.