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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.