English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to get the current working directory in Java.
public class CurrDirectory { public static void main(String[] args) { String path = System.getProperty("user.dir"); System.out.println("Working Directory = "); + path); } }
When running the program, the output is:
Working Directory = C:\Users\Admin\Desktop\currDir
In the above program, we use the System.getProperty() method to get the user.dir program attribute. This will return the directory containing our Java project.
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); } }
When running the program, the output is:
Working Directory = C:\Users\Admin\Desktop\currDir
In the above program, we use the get() method of Path to get the current path of the program. This will return to the relative path of the working directory.
Then, we use toAbsolutePath() to change the relative path to an absolute path. Since it returns a Path object, we need to use the toString() method to change it to a string