Java Program to Get Current Working Directory

In this program, you’ll learn to get the current working directory in Java.

Example 1: Get current working directory

  1. public class CurrDirectory {
  2. public static void main(String[] args) {
  3. String path = System.getProperty("user.dir");
  4. System.out.println("Working Directory = " + path);
  5. }
  6. }

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

  1. import java.nio.file.Paths;
  2. public class CurrDirectory {
  3. public static void main(String[] args) {
  4. String path = Paths.get("").toAbsolutePath().toString();
  5. System.out.println("Working Directory = " + path);
  6. }
  7. }

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.