Kotlin – Get File Extension

Kotlin – Get File Extension

To extract the file extension from a file path or a file object in Kotlin, you can use the File class from the java.io package. The File class provides an easy way to obtain the extension of a file from its name using File.extension property.

In this tutorial, we will show you how to get the file extension of a file in Kotlin, with an example.

Steps to Get the File Extension in Kotlin

To retrieve the file extension in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object by specifying the file path.
  3. Use the extension property of the File object to get the file’s extension.

Kotlin Example Program to Get File Extension

In the following program, we demonstrate how to obtain the file extension for a file named 'example.txt'.


import java.io.File

fun main() {
    val filePath = "path/to/your/file/example.txt" // Replace with your file path

    val file = File(filePath)
    val fileExtension = file.extension

    println("The file extension is: $fileExtension")


The file extension is: txt

The output will display the extension of the file.


In this Kotlin tutorial, we learned how to get the extension of a file using File.extension property, with an example.