Java Get Current Working Directory Example

To find the current working directory for any application (i.e. root folder of the application) in java you can use given below methods.

1. System.getProperty(“user.dir”)

System.getProperty("user.dir") statement will output the root folder of your current Java project.

Example 1: Java get current working directory from system properties

public class Main 
{
	public static void main(String[] args) 
	{
		String currentWorkingDir = System.getProperty("user.dir");
		System.out.println(currentWorkingDir);
	}
}

output:

C:\Users\lokesh\workspaceluna\JavaExamples

2. Paths.get().toAbsolutePath()

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

Example 2: Java get current working directory in Java 8

In the given example, Paths.get("") is used to build a relative path to itself. Using this path, we can get the absolute path of the current working directory.

public class Main 
{
	public static void main(String[] args) 
	{
		Path currentWorkingDir = Paths.get("").toAbsolutePath();
		System.out.println(currentWorkingDir.normalize().toString());
	}
}

output:

C:\Users\lokesh\workspaceluna\JavaExamples

Please do not forget to use normalize() method for correct result.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.