Reputation: 9785
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".
Upvotes: 2
Views: 2653
Reputation: 1282
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.
Upvotes: 2
Reputation: 41142
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.
Upvotes: 0
Reputation: 13888
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;
}
Upvotes: 0