开发者

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

This question already has answers here: How to get the path of a running JAR file? 开发者_如何学Go (33 answers) Closed 9 years ago.

I'm running a jar file in various locations and I'm trying to figure out how to get the location of the jar file that is running.


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

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


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()


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;
}


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];
        }


This seems like an iffy question to start out with.

If I am running code in Java, it is running out of rt.jar and probably a dozen other jars.

The very first files to run will actually be in rt.jar, rt.jar it calls your main.

If you write a class that allows you to tell what jar you are running and that class gets moved into a different jar, then you are not "running out of" the jar that contained your main any more.

I think what you want is the command line that started your application, but if you CD'd to the directory first, then it might not have the full path to your jar.

Also, you may not be running from a jar--someone could have expanded your jar into classes in a directory and is running it that way.

Personally I'd just wrap your program in a shell script launcher where you could look at your current location and the location of the jar file and then pass them into java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜