Get Current Working Directory in Java

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”)

In Java, 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()

If we are working on Java 7 or higher then a rather better approach is to use the latest Path APIs for finding the current working directory.

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 !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.