Friday, November 12, 2021

[SOLVED] Java get path of dir of java file where main is located

Issue

I need to get the path of a directory. The directory contains the java file where the main method is found.

So I have already searched stackoverflow but still did not find an answer.

I have already used the following but with no success:

  1. File file = new File("name.java"); String path = file.getCanonicalPath(); System.out.println(path);

    Output is: /home/aaa/dev/robot/name.java

  2. String cwd = System.getProperty("user.dir"); System.out.println("Current working directory : " + cwd);

    Current working directory : /home/aaa/dev/robot

  3. File resourcesDirectory = new File("src/test/resources"); System.out.println(resourcesDirectory.getAbsolutePath());

    /home/aaa/dev/robot/src/test/resources

What I actually need is the following:

/home/aaa/dev/robot/src/main/java/com/aaa/robot

in which the name.java is found.

I am in linux mint.


Solution

This will help you:

import java.io.File;

public class Test {

    public static void main(String[] args) {
        String name = Test.class.getName().replace(".", File.separator);
        String path = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + name.substring(0, name.lastIndexOf(File.separator));
        System.out.println(path);
    }

}


Answered By - M o