Getting the path of the program's jar file

M

mic123

Hey everyone,
Is there a java method that can help me obtain the path of the jar file
of the currently running program (from within the program itself)?

For example, if my jar's name is a.jar I want to be able to print a.jar
in the main app (dynamically of course)
 
T

Thomas Fritsch

Hey everyone,
Is there a java method that can help me obtain the path of the jar file
of the currently running program (from within the program itself)?
Which jar file? Usually a Java application has more than 1 jar files.
For example, if my jar's name is a.jar I want to be able to print a.jar
in the main app (dynamically of course)
URL url =
YourClass.class.getProtectionDomain().getCodeSource().getLocation();

You should get something like file://yourDirectory/a.jar or
http://www.yourServer.com/yourDirectory/a.jar

But there are issues with this approach:
getProtectionDomain() may throw a SecurityException
getCodeSource() may return null

See also the API docs of
java.lang.Class#getProtectionDomain
java.security.ProtectionDomain#getCodeSource
java.security.CodeSource#getLocation
 
P

Paul Davis

This should give you what you are looking for:

String resName = this.getClass().getName().replace('.','/')+".class";
String url = ClassLoader.getSystemResource(resName).getPath();

Just chop up the string to get what you need
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top