6

i'm trying to find the location of the running jar file using the method:

File jarFile = new File(JarPath.class.getProtectionDomain().getCodeSource().getLocation().toURI());

when i run it on the IDE (eclipse) it returns the correct path. but when i run the jar as an executable the code source returned is

rsrc:./

ideas on how the get the correct path?

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
IdoS
  • 63
  • 9

1 Answers1

3

Try a different approach to get the location.

String jarFilePath = ClassLoader.getSystemClassLoader().getResource(".")
        .toURI()
        .getPath()
        .replaceFirst("/", "");

This gives you up to the parent location of the jar file.

C:/Users/Roshana Pitigala/Desktop/

You still need to add the filename and the extension (jarFileName.jar).

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
  • 1
    Don’t use the class loader when looking up a class’ resources. This can break as soon as modules are involved, as that information is missing. You can use `JarPath.class.getResource("JarPath.class")`, which is simpler than `JarPath.class.getClassLoader().getResource(JarPath.class.getName().replace('.', '/') + ".class")` and works in a modular environment, as still having the `Class` implies knowing the associated module. – Holger Nov 05 '18 at 14:59
  • This does not work. The `getPath()` throws a `NullPointerException`, and the `toURI()` gives the fully qualified class name, not the path to the jar! – user7291698 Nov 05 '18 at 16:14
  • @user7291698 try now. I've updated the answer as Holger suggested. Btw upto `getPath()` it should return the path to the class not the jar. The idea is to get the path to the class and remove the unnecessary parts. – Roshana Pitigala Nov 05 '18 at 17:27
  • Your solution only works when you create the jar using the Eclipse option "Extract required libraries into generated JAR". But I need a solution that works with the option "Package required libraries into generated JAR"! – user7291698 Nov 05 '18 at 17:49
  • @user7291698 Check the answer now. It's tested, and working. – Roshana Pitigala Nov 05 '18 at 19:00
  • Great, now it works, thank you! I will give you the bounty, but would appreciate an additional hint how to get the name of the jar-file itself, in case the user renames the jar-file. – user7291698 Nov 05 '18 at 20:06
  • @user7291698 yeah, I'll keep trying and update the answer as soon as I find a solution. – Roshana Pitigala Nov 05 '18 at 20:38