Current working directory when starting Jar

I created an application that is an executable bank (using the maven-assembly plugin) with several user-configurable resources that are located next to it in the same directory (images, properties, etc.).

When you run jar from the command line with java -jar ... current directory will be what you expected. The problem is that on some operating systems (Ubuntu 11.04), if the application is launched by simply double-clicking on jar, then the current working directory is the home directory.

Is there a preferred way to get the current directory in which the bank is located, or another method for accessing external resources that are located next to the bank?

+8
java jar
source share
2 answers

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

Another alternative would be to place other read-only resources in your jarfile along with the associated classes so that you can use Class.getResource (String) or Class.getResourceAsStream (String) to get resources relative to this class.

For example, you might have the class com.example.icons.Icons, and the icons will be packaged with Icons.class in the com / example / myapp / icons / directory. Suppose your open button uses an icon called open.png:

 ImageIcon icon = new ImageIcon(Icons.getResource("open.png")); 
+11
source share

Here is my attempt to find the directory from which the bank 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 create a "path" of the current class, replacing ".". "/", then I extract the class as a resource. The toString () method returns something like:

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

From there you will parse this line to get the directory in which the jar is located.

+1
source share

All Articles