Java - How to get the current working directory

How to get the current working directory during program execution. There are two ways to get it from system properties and to convert the current relative path to an absolute path. You can get the path to the working location with System.getProperty("user.dir").

Get working directory with System.getProperty

Get the system property for "user.dir" to get the current working path.

public class Example {
  public static void main(String args[]) {
      String path = System.getProperty("user.dir");
      System.out.println("Working Directory = " + path);
  }
}

Print

Working Directory = /home/user/testcode/java

Convert from relative to absolute

There is a way to first find the relative path to the current directory and convert it to an absolute path.

import java.nio.file.Paths

public class Example {
  public static void main(String args[]) {
      Path relativePath = Paths.get("");
      String path = relativePath.toAbsolutePath().toString();
      System.out.println("Working Directory = " + path);
  }
}

Print

Working Directory = /home/user/testcode/java

Clean up

You have learned how to get the path of the current working directory.

codechachaCopyright ©2019 codechacha