Myclass.class.getProtectionDomain().getCodeSource() return empty path
Asked Answered
R

1

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?

Rostock answered 17/8, 2015 at 12:16 Comment(2)
I have the same problem, so far I found out that this happens when you use the option "Package required libraries into generated JAR" when generating the jar in Eclipse.Mina
No repo in NetBeansCreosote
C
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).

Creosote answered 3/11, 2018 at 14:44 Comment(7)
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.Rozier
This does not work. The getPath() throws a NullPointerException, and the toURI() gives the fully qualified class name, not the path to the jar!Mina
@Mina 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.Creosote
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"!Mina
@Mina Check the answer now. It's tested, and working.Creosote
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.Mina
@Mina yeah, I'll keep trying and update the answer as soon as I find a solution.Creosote

© 2022 - 2024 — McMap. All rights reserved.