Java Program to Get Current Working Directory

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Get current working directory

public class CurrDirectory {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir");
        
        System.out.println("Working Directory = " + path);

    }
}

Output

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 the current working directory using Path

import java.nio.file.Paths;

public class CurrDirectory {

    public static void main(String[] args) {

        String path = Paths.get("").toAbsolutePath().toString();
        System.out.println("Working Directory = " + path);

    }
}

Output

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 an absolute path using toAbsolutePath(). Since it returns a Path object, we need to change it to a string using toString() method.

Did you find this article helpful?