Reputation: 440
There are plenty of folders that let you find the folder that the running jar is in, but how do I get the running jar? For example, if foo.jar is in C:/FOO/foo.jar, then how would I get the path C:/FOO/foo.jar, not C:/FOO. Also, I have no idea A: if the jar was moved to a different folder, B: If my jar was renamed, and C: if there are other jars in the same folder as mine. I want to get a File object of the currently running jar, which I am then going to be using (in some way) to replace that jar with a new version of my program. Can anyone help me with this? Thanks! EDIT: Wait a minute, would it be possible to, after finding the directory, scan through it looking for jar files, and in each jar file, check for a certain class/other file that is in my jar?
Upvotes: 2
Views: 7281
Reputation: 440
Alright, I got it figured out. It's something like this:
File dir = new File(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
String jar = System.getProperty("java.class.path");
File jarFile = new File(dir, jar);
Thanks everyone! EDIT: Also, if I ever end up with multiple jars in the classpath, I would need something to check that I got the right one.
Upvotes: 5
Reputation: 920
In order to get the path of jar, use:
File dir = new File(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
To get the main class name, use:
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
Then, use them all together:
File f = new File(dir, mainClass);
Upvotes: 0
Reputation: 759
You can use find file JAVA API.
What you want is File.listFiles(FileNameFilter filter).
That will give you a list of the files in the directory you want that match a certain filter.
The code will look similar to
Upvotes: -1