How do I get the directory that the currently executing jar file is in? [duplicate]

Solution 1:

Not a perfect solution but this will return class code base’s location:

getClass().getProtectionDomain().getCodeSource().getLocation()

Solution 2:

As noted in the comments, this is not a direct answer to the question, but may actually be what many people are looking for (the current directory of the executing code):

new File(".").getAbsolutePath()

Solution 3:

Here is my method to get execution path from anywhere

private static String GetExecutionPath(){
    String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("/"));
    absolutePath = absolutePath.replaceAll("%20"," "); // Surely need to do this here
    return absolutePath;
}

Solution 4:

Consider the following function

 //This method will work on Windows and Linux as well.    
     public String getPath(){
        URL rootPath = getClass().getResource("");
        String URI=rootPath.toString().substring(9);
        String[] currentPath=URI.split("myjar.jar!");
        currentPath[0]=currentPath[0].replaceAll("%20"," ");
        return currentPath[0];
        }