1

How do I get the location of the executed jar? I found a lot of solutions but none of them work for me. When I run them in my IDE everything is fine. As soon as I build a jar file and run it with java -jar myapp.jar the output is like /.../myapp.jar!/foo/bar

I will run the code in myapp.jar - not in any library.

Location of jar: /home/me/dev/myapp/myapp.jar
Expected output: /home/me/dev/myapp/

I don't want the working directory as I would get with System.getProperty("user.dir");

Why I want to do this:

I want to store and load a file beside the actual jar. Like

/home/me/bin/myapp/myapp.jar
/home/me/bin/myapp/license.key

I want to avoid storing the file into some generic folder like System.getProperty("user.home");. And I don't want to store the file within the jar file.

boop
  • 7,413
  • 13
  • 50
  • 94

2 Answers2

0

java.nio.file.Paths.get(".").toAbsolutePath() will return absolute path to current directory.

dsavickas
  • 1,360
  • 1
  • 9
  • 12
  • I quote my question here: "I don't want the working directory" – boop Sep 16 '15 at 14:42
  • Try creating simple class which simply prints `Paths.get(".").toAbsolutePath()` to stdout and create jar file containing this class. Then move this jar file to different folders and run `java -jar test.jar`. I saw name of directory where jar file is located printed to stdout. I assumed this is what you want. – dsavickas Sep 16 '15 at 14:51
  • `cd /tmp && java -jar /home/me/myapp.jar` would result in `/tmp/` - not what I want. I want `/home/me/` – boop Sep 16 '15 at 14:56
0

I use something along these lines:

[YourClass].class.getProtectionDomain().getCodeSource().getLocation().getPath()

Regards