Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the path of a running JAR file?

My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.

So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.

like image 585
Thiago Chaves Avatar asked Nov 26 '08 12:11

Thiago Chaves


People also ask

How do I find the path of a JAR file?

In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName. class . getProtectionDomain() .

How do I find the path of a file in Java?

In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.


2 Answers

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.

like image 133
Zarkonnen Avatar answered Oct 16 '22 02:10

Zarkonnen


Best solution for me:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); 

This should solve the problem with spaces and special characters.

like image 20
Fab Avatar answered Oct 16 '22 04:10

Fab