Exercise:
Write a Java Program to get current working directory.
1.Display without using path
Click Here to View the Solution!
public
class GetCurrDirectory {
public static void main(String[] args) {
String path = System.getProperty(
"user.dir");
System.out.println(
"Current Working Directory = " + path);
}
}
Click Here to View the Output!
Current Working Directory = C:\Users\Admin\Desktop\currDir
Click Here to View the Explanation!
For retrieving the directory which contains the java project, a system’s method called getProperty()
is utilized with user.dir
passed as the property to be retrieved in the method’s argument. This returns the path of the current directory.
2.Display using path
Click Here to View the Solution!
import java.nio.file.Paths;
public
class CurrDirectory {
public static void main(String[] args) {
String path = Paths.get(
"").toAbsolutePath().toString();
System.out.println(
"Working Directory = " + path);
}
}
Click Here to View the Output!
Working Directory = C:\Users\Admin\Desktop\currDir
Click Here to View the Explanation!
In this program, the path of the current directory is retrieved through the get()
method of the Path class
in Java. The get()
method returns the location in the form of a relative path. In order to convert it into an absolute path, .toAbsolutePath()
is used. Furthermore, since this method returns object type path, it is converted into String type using the toString()
method.