Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of running Jar or Exe

Tags:

java

jar

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?

like image 270
user1947236 Avatar asked Jan 07 '13 02:01

user1947236


People also ask

How do I get the path of a jar?

In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .

Is .exe same as jar?

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.

What is JAR file name?

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.

How can I tell which class a jar was loaded from?

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.


2 Answers

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?

like image 115
Christopher Cabezudo Rodriguez Avatar answered Nov 24 '22 07:11

Christopher Cabezudo Rodriguez


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('!')));
}
like image 21
Alexander Avatar answered Nov 24 '22 09:11

Alexander