How to get the current working directory in Java?
How to get the current working directory in Java?
Question
I want to access my current working directory using java.
My code :
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("Current dir:"+current);
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 ?
Popular Answer
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
This will print a complete absolute path from where your application was initialized.
From the documentation:
java.io
package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir
and is the directory from where the JVM was invoked.
Read more… Read less…
See: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Using java.nio.file.Path
and java.nio.file.Paths
, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
This outputs Current relative path is: /Users/george/NetBeansProjects/Tutorials
that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.
The following works on Java 7 and up (see here for documentation).
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();
This will give you the path of your current working directory:
Path path = FileSystems.getDefault().getPath(".");
And this will give you the path to a file called "Foo.txt" in the working directory:
Path path = FileSystems.getDefault().getPath("Foo.txt");
Edit : To obtain an absolute path of current directory:
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
* Update * To get current working directory:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
I've found this solution in the comments which is better than others and more portable:
String cwd = new File("").getAbsolutePath();
Or even
String cwd = Paths.get("").toAbsolutePath();