What I need to do is get the name of the running jar/exe file (it would be an EXE on windows, jar on mac/linux). I have been searching around and I can't seem to find out how.
How to get name of running Jar or Exe?
In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .
An Exe file is an executable file that can be executed in Microsoft OS environment. Jar file is container of Java Class files, including other resources related to the project. Jar file can be executed only if Java run time environment.
JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one.
Use –verbose:class flag with your java command line. This option enables loading and unloading of classes. It shows the jar file from which the class is loaded.
Hope this can help you, I test the code and this return you the full path and the name.
Maybe you want to play a little more with the code and give me some feed back.
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
This was found on a similar but not == question on stackoverflow How to get the path of a running JAR file?
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
returns simple path in the compiled application and an error in jar:
URI is not hierarchical
My solution is:
private File getJarFile() throws FileNotFoundException {
String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n" + path);
}
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return new File(path.substring(0, path.lastIndexOf('!')));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With