Getting the current working directory in Java means getting the path of the directory (folder) from where your program has launched. Normally, that means to get the path from the root folder to the folder where the program file has been placed. This is a common day to day problem and there are multiple ways to do it in Java. However, we will start with the most basic one utilising the System’s built-in method.
Using System.getProperty(); Method
public class DriverClass {
public static void main(String[] args) {
String userDirectoryPath = System.getProperty("user.dir");
System.out.println("Current Directory = \"" + userDirectoryPath + "\"" );
}
}
Output
Current Directory = "C:\Users\DELL\eclipse-workspace\JavaProjects"
Explanation
The above code snippet uses the “getProperty()” method provided by the “System” with the standard parameter “user.dir”. It fetches the path of the directory containing your Java project. Run it for yourself and you will see it is printed in the output.Using the java.nio.file.FileSystems
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class DriverClass1 {
// Print Current Working Directory using File Systems
static void printCurrentWorkingDirectoryUsingFileSystems() {
Path currentDirectoryPath = FileSystems.getDefault().getPath("");
String currentDirectoryName = currentDirectoryPath.toAbsolutePath().toString();
System.out.println("Current Directory = \"" + currentDirectoryName + "\"");
}
public static void main(String[] args) {
printCurrentWorkingDirectoryUsingFileSystems();
}
}
Output
Current Directory = "C:\Users\DELL\eclipse-workspace\JavaProjects"