Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to get the current working directory in Java?

I want to access my current working directory using Java.

My code:

String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);

String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);

Output:

Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32

My output is not correct because C drive is not my current directory.

How to get the current directory?
by

2 Answers

Kajalsi45d
Java 11 and newer
This solution is better than others and more portable:

Path cwd = Path.of("").toAbsolutePath();

Or even

String cwd = Path.of("").toAbsolutePath().toString();
MounikaDasa
Code :

public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
This will print the absolute path of the current directory from where your application was initialized.

Login / Signup to Answer the Question.