开发者

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

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

I'm asking that, 开发者_如何学Cbecause of the loading resources like pictures, templates etc. Inside a JAR file it will be different.

Thank you in advance.


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.


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


Use getResourceAsStream to attempt to retrieve the resource. If you are not running in a jar, or the resource cannot be found, the method returns null. In that case you're not running in a jar and must use a FileInputStream or other method to retrieve your resource.

Strictly speaking, this retrieves resources that are on the classpath, but the effect is pretty much what you appear to need.


The application starts with a main method in some Class, let's call it com.example.Main.

You can use this code to print the URL of the class file that has been used to load it:

System.out.println(ClassLoader.getSystemResource("com/example/Main.class"));

This is the URL that has been used to load your applications main class and, if the URL String starts with jar:file:, then the class file has been loaded from a jar.


You could potentially determine it by inspecting the java.class.path system property. That's unlikely a good idea however. Instead you should use Class.getResourceAsStream(). Then just put your assets in your project under the same logical directory structure as they as packaged into the jar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜