8

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?

job
  • 9,003
  • 7
  • 41
  • 50

2 Answers2

11

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"));
rob
  • 6,147
  • 2
  • 37
  • 56
  • The first chunk of code works for the jar but breaks when I run from within eclipse (unless I move the files). Unfortunately, packaging the resources inside the jar isn't an option because the user may need to configure them. – job Jun 22 '11 at 01:04
1

Here my attempt to discover the directory from where a jar is running.

public class JarLocation {
    public static void main(String[] args) {
        new JarLocation().say();
    }

    public void say() {
        String className = this.getClass().getName().replace('.', '/');
        String classJar =  
            this.getClass().getResource("/" + className + ".class").toString();
        if (classJar.startsWith("jar:")) {
            System.out.println("*** running from jar!");
        }
        javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
                null, classJar, "jar location",
                javax.swing.JOptionPane.DEFAULT_OPTION);
    }
}

First I build the "path" of the current class by replacing the "." by "/", then I retrieve the .class as a Resource. The toString() method returns something like :

jar:file:/C:/temp/testing.jar!/my/package/JarLocation.class

From there your parse the given string to retrieve the directory where the jar is.

RealHowTo
  • 34,977
  • 11
  • 70
  • 85