English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Get Current Working Directory

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to get the current working directory in Kotlin.

Example1:Get the current working directory

fun main(args: Array<String>) {
    val path = System.getProperty("user.dir")
    println("Working Directory = $path")
}

When running the program, the output is:

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

In the above program, we use the System's getProperty() method to get the program's user.dir attribute. This will return the directory containing our Java project.

Example2:Get the current working directory using path

import java.nio.file.Paths
fun main(args: Array<String>) {
    val path = Paths.get(
    println("Working Directory = $path")
}

When running the program, the output is:

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

In the above program, we use the Path's get() method to get the current path of the program. This will return to the relative path of the working directory.

Then, we use the toAbsolutePath() method to change the relative path to an absolute path. Since it returns a Path object, we need to use the toString() method to change it to a string.

The following is the equivalent Java code:Java Program to Get Current Working Directory.

Comprehensive Collection of Kotlin Examples