Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current working directory when running a Jar

Tags:

java

jar

I've created an application that is a runnable jar (using maven-assembly plugin) with a couple of user-configurable resources that sit along side it in the same directory (images, properties, etc.)

When running the jar from the command line with java -jar ... the current directory is as you would expect. The problem is that on some operating systems (Ubuntu 11.04), if the application is started by simply double clicking the jar then the current working directory is the home directory.

Is there a preferred way of getting the current directory that the jar is in, or another method altogether for accessing external resources that sit alongside the jar?

like image 839
job Avatar asked Jun 22 '11 00:06

job


1 Answers

You can use MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath() to get the location of the jarfile.

Another alternative would be to package the other read-only resources in your jarfile alongside related classes so you can use Class.getResource(String) or Class.getResourceAsStream(String) to get resources relative to the given class.

For example, you might have a class com.example.icons.Icons, and the icons would be packaged alongside Icons.class in the com/example/myapp/icons/ path. Suppose your "open" button uses an icon named open.png:

ImageIcon icon = new ImageIcon(Icons.getResource("open.png"));
like image 59
rob Avatar answered Sep 27 '22 19:09

rob