tags:

views:

85

answers:

3

How do I get the path of a an executed .jar file, in Java?

I tried using System.getProperty("user.dir"); but this only gave me the current working directory which is wrong, I need the path to the directory, that the .jar file is located in, directly, not the "pwd".

A: 

Taken From Java-Forumns:

        public static String getPathToJarfileDir(Object classToUse) {
        String url = classToUse.getClass().getResource("/" + classToUse.getClass().getName().replaceAll("\\.", "/") + ".class").toString();
        url = url.substring(4).replaceFirst("/[^/]+\\.jar!.*$", "/");
        try {
            File dir = new File(new URL(url).toURI());
            url = dir.getAbsolutePath();
        } catch (MalformedURLException mue) {
            url = null;
        } catch (URISyntaxException ue) {
            url = null;
        }
        return url;
      }
LnDCobra
This does not work, returns the path to the JRE when used as instructed. Thanks though!
Zolomon
A: 

Perhaps java.class.path property?

If you know the name of your jar file, and if it is in the class path, you can find its path there, eg. with a little regex.

PhiLho
+1  A: 
elou
Need to get access to the config.ini file that is stored in the same directory as the .jar file.
Zolomon
Have a look at ClassLoader#getResource / #findResource.
elou
@elou: not sure if it can work if the config file is external to the jar.
PhiLho
This only works if the resource is in your classpath. If not you, to know where it is located and create an InputStream to access its content.
elou