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?
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"));
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