How to Get the Path of a Running Jar File

How to get the path of a running JAR file?

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();

Replace "MyClass" with the name of your class.

Obviously, this will do odd things if your class was loaded from a non-file location.

How do I get the directory that the currently executing jar file is in?

Not a perfect solution but this will return class code base’s location:

getClass().getProtectionDomain().getCodeSource().getLocation()

Get location of JAR file

Update

Since it doesn't work in certain test-cases, I'll update the answer.

The correct way to do this should be with ClassLoader:

File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
System.out.println(jarDir.getAbsolutePath());

Tested on various classpaths, the output was correct.


Old answer

This should work

File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();

It works for me, my program is in:

C:\Users\User01\Documents\app1\dist\JavaApplication1.jar

And it returns

C:\Users\User01\Documents\app1\dist

How to get Jar File Path

Use URL Class.getResource(String name) method.

package.ClassName.class.getClassLoader().getResource("package.ClassName");

EDIT:

Have a look at great SO thread - How to get the path of a running jar file? suggested by @Hovercraft Full Of Eels

How can I get the path of the compiled jar file via code?

You can use Path to do this:

Path path = Paths.get(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

Path have several methods to get more information.

For example, i have this JAR in Desktop and i am printing this:

System.out.println(path);
System.out.println(path.getRoot());
System.out.println(path.getParent());

The results are:

java -jar C:\Users\gmunozme\Desktop\Test.jar
C:\Users\gmunozme\Desktop\Test.jar
C:\
C:\Users\gmunozme\Desktop

Check that out,
Hope you can use it.

How to get the path of a directory where my running jar file is?

CodeSource.getLocation() gives you a URL, you can then create new URLs relative to that:

URL jarLocation = XMLParser.class.getProtectionDomain().getCodeSource().getLocation();
URL dataXML = new URL(jarLocation, "SomeData/SomeFolder/data.xml");

You can't simply do new File(...getCodeSource().getLocation().getPath()) as a URL path is not guaranteed to be a valid native file path on all platforms. You're much safer sticking with URLs and passing the URL directly to your XML parser if you can, but if you really need a java.io.File then you can use an idiom like this to create one from a URL.



Related Topics



Leave a reply



Submit