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.
5 Answers
Not a perfect solution but this will return class code base’s location:
getClass().getProtectionDomain().getCodeSource().getLocation() 9 Comments
cd /somefolder and then java -jar /otherfolder/file.jar then other suggestions would return /somefolder. +1./otherfolder?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() 2 Comments
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; } 2 Comments
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]; } Comments
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.
String path = new File(".").getCanonicalPath().toString();