Java Program to Get Current Working Directory

In this java program, we will learn about how to get the current working directory in Java. It should be noted that Java lacks native functionality for directly obtaining the current working directory, therefore we must resolve it relatively.

To get the current working directory in Java we will use java.lang.System and java.io.File class.


Java Program to Display Current Working Directory using System.getProperty method

The method java.lang.System.getProperty() is used to obtain the system property. This system property is specified by the key which is the parameter for the method. We used a Java built-in property key user.dir to fetch the current working directory from the System‘s property map.

public class CurrentDirectoryUsingSystem {
  public static void main(String args[]) {
    String currentDir = System.getProperty("user.dir");
    System.out.println("Current Directory is: " + currentDir);
  }
}
Output
/Users/tcc/workplace/programs

In above java program, the current working directory is obtained by using the key "user.dir" with the method java.lang.System.getProperty(). Then the current working directory is printed using System.out.println() method.


Java Program to Display Current Working Directory using File class

Here, we will call getAbsolutePath() method of File class to get the directory name. Similar to our first solution, it internally uses System.getProperty() method to get the directory name.

import java.io.File;

public class CurrentDirectoryUsingFile {
  public static void main(String args[]) {
    String currentDir = new File("").getAbsolutePath();
    System.out.println("Current Directory is: " + currentDir);
  }
}
Output
/Users/tcc/workplace/programs