Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if the program run in JAR or not?

Tags:

java

jar

How can I detect if the program runs in JAR or not?

I'm asking that, because of the loading resources like pictures, templates etc. Inside a JAR file it will be different.

Thank you in advance.

like image 258
Alex Avatar asked Dec 28 '22 22:12

Alex


2 Answers

I'm asking that, because of the loading resources like pictures, templates etc. Inside a JAR file it will be different.

No, it won't, if you do it correctly.

This will work exactly the same whether the class is loaded from a directory, a webserver or a JAR file:

ImageIcon icon = new ImageIcon(getClass().getResource("logo.gif"));

Alternatively, use the getResourceAsStream() method for maximal flexibility.

like image 134
Michael Borgwardt Avatar answered Jan 10 '23 04:01

Michael Borgwardt


Examine getClass().getProtectionDomain().getCodeSource().getLocation(); - this'll give you a directory or a jar.

like image 23
Erik Avatar answered Jan 10 '23 04:01

Erik