2

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".

Zolomon
  • 9,359
  • 10
  • 36
  • 49

3 Answers3

2

Could you specify why you need the path?
If you need to access some property from the jar file you should have a look at ClassLoader.getSystemClassLoader();
don't forget that your classes are not necessary store in a jar file.


// if your config.ini file is in the com package.
URL url = getClass().getClassLoader().getResource("com/config.ini");
System.out.println("URL=" + url);

InputStream is = getClass().getClassLoader().getResourceAsStream("com/config.ini");
try {
    if (is != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
    else {
        System.out.println("resource not found.");
    }
}
catch (IOException e) {
    e.printStackTrace();
}

regards.

elou
  • 1,242
  • 15
  • 21
  • Need to get access to the config.ini file that is stored in the same directory as the .jar file. – Zolomon Mar 01 '10 at 13:37
  • Have a look at ClassLoader#getResource / #findResource. – elou Mar 01 '10 at 13:55
  • not sure if it can work if the config file is external to the jar. – PhiLho Mar 01 '10 at 13:57
  • 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 Mar 01 '10 at 14:09
0

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;
      }
Michal Ciechan
  • 13,492
  • 11
  • 76
  • 118
0

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
  • 40,535
  • 6
  • 96
  • 134