Get the Current Working Directory in Java

How do you get the current working directory in Java? There are a few different ways of getting the the current working directory.
System Property user.dir
The System class contains properties that describes the configuration of the current working environment. The property that returns the current working directory is “user.dir”.
String userDir = System.getProperty("user.dir");
System.out.println("The current working directory is: " + userDir);
File Class
You can use the File class to get the current working directory. Create a new File instance and call the getAbsolutePath method.
String userDir = new java.io.File("").getAbsolutePath()
System.out.println("The current working directory is: " + userDir);
Paths Class
You can use the Paths class to find the current working directory. The Paths class has a static get method that returns a Path instance. This solution only works on Java version 7 or higher.
String userDir = java.nio.file.Paths.get("").toAbsolutePath().toString();
System.out.println("The current working directory is: " + userDir);
FilesSystems Class
The FilesSystems class can also be used to retrieve the current working directory. The FilesSystems class has a static getDefault() method that will allow you to get the current path.
String userDir = java.nio.file.FileSystems.getDefault().getPath("").toAbsolutePath().toString();
System.out.println("The current working directory is: " + userDir);
Recommendation
Even though all of the above methods yield the same result, my recommendation is to use the system property “user.dir”.
Comments
Leave a Comment