Search code examples
javalinuxjarworking-directory

Java: Howto know where the jar is located in Linux


In Linux, the JVM sets the working direcory equal to the homefolder from the user. In Windows is this the folder where the jar is located. How can I find where the jar (from my app) is located to change the working dir?

Martijn


Solution

  • Try obtaining the path to the jar with this code:

    String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
    

    Then you can remove the "*.jar" part with:

    path=path.substring(0, path.lastIndexOf('/')+1);
    

    I had the same problem with a java game when I needed to open a file in the same directory the jar was.

    Double clicking the jar in linux didn't open the file. Of course you can open a command line and change dir to the jar dir and then run the jar from there but I needed to double click the jar.