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?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges