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.
If the jar was launched from its own directory (i.e. java -jar File.jar
), the following will do:
System.getProperty("user.dir");
Another method would be
new File (".").getCanonicalPath();
getCanonicalPath()
does a few useful things. From the docs:
This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath() method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
Not a perfect solution but this will return class code base’s location:
getClass().getProtectionDomain().getCodeSource().getLocation()
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.