Java Get Root Directory: 2 Methods

In Java, you can obtain the root directory of a project using the following method:

  1. Typically, the current working directory can be obtained using the System.getProperty(“user.dir”) method, and this directory is usually the root directory of the project.
String rootDirectory = System.getProperty("user.dir");
System.out.println("Root Directory: " + rootDirectory);
  1. Use the getResource() method of the ClassLoader class to retrieve the root directory of the project.
ClassLoader classLoader = getClass().getClassLoader();
URL rootUrl = classLoader.getResource("");
String rootDirectory = new File(rootUrl.getPath()).getAbsolutePath();
System.out.println("Root Directory: " + rootDirectory);

You can use either of these two methods to get the root directory of the project, just choose the one that suits your needs.

bannerAds