Kotlin Program to Get Current Working Directory

Example 1: Get current working directory

fun main(args: Array<String>) {

    val path = System.getProperty("user.dir")

    println("Working Directory = $path")

}

When you run the program, the output will be:

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we used System's getProperty() method to get the user.dir property of the program. This returns the directory which contains our Java project.


Example 2: Get current working directory using Path

import java.nio.file.Paths

fun main(args: Array<String>) {

    val path = Paths.get("").toAbsolutePath().toString()
    println("Working Directory = $path")

}

When you run the program, the output will be:

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we used Path's get() method to get the current path of our program. This returns a relative path to the working directory.

We then change the relative path to absolute path using toAbsolutePath(). Since, it returns a Path object, we need to change it to a string using toString() method.

Here's the equivalent Java code: Java program to get current working directory.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community