Kotlin – Get Absolute File Path

Kotlin – Get Absolute File Path

To get the absolute path of a file in Kotlin, you can use the absolutePath property of the File class from the java.io package.

The absolute path is the complete path to the file in the file system, starting from the root directory.

In this tutorial, we will go you through the process of getting the absolute path of a file using Kotlin.

Steps to Get the Absolute File Path in Kotlin

To retrieve the absolute file path in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object with the relative or absolute file path.
  3. Use the absolutePath property of the File object to get the file’s absolute path.

Kotlin Example Program to Get Absolute File Path

In the following program, we demonstrate how to get the absolute path of a file named 'example.txt'.

Main.kt

import java.io.File

fun main() {
    val relativeFilePath = "example.txt" // Replace with your relative file path
    val file = File(relativeFilePath)

    val absolutePath = file.absolutePath
    println("The absolute file path is: $absolutePath")
}

Output

The absolute file path is: /Users/kotlinandroid/IdeaProjects/KotlinApp/example.txt

The output will display the absolute path of the file on your file system.

Summary

In this Kotlin tutorial, we learned how to retrieve the absolute path of a file. This method is essential for applications that require a full file path, such as file manipulation and path validation tasks.