Learn to find the current working directory for any application using the Java APIs. Note that Java does not have native support for getting the present working directory directly, so we must resolve it relatively.
1. Using System.getProperty(“user.dir”)
user.dir property is the directory where
java command was run from. In other words, it outputs the location where the application was started. So,
System.getProperty("user.dir") statement will output the root folder of our current Java project.
String currentWorkingDir = System.getProperty("user.dir");
2. Using NIO Paths.get().toAbsolutePath()
In the given example,
Paths.get("") is used to build a relative path to itself. Using this path, we can normalize to the absolute path of the current working directory.
Path currentWorkingDir = Paths.get("").toAbsolutePath(); System.out.println(currentWorkingDir.normalize().toString());
Please do not forget to use normalize() method for the correct results.
Happy Learning !!