Java: how to find out where jar is in Linux?

On Linux, the JVM sets a working directory equal to the user's home folder. On Windows, this is the folder where the jar is located. How do I find where the jar is (from my app) to change the working directory?

Martijn

+2


source to share


2 answers


Try to get the jar path 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 where I needed to open a file in the same directory as the jar.

Double clicking on the jar in Linux did not open the file. You can of course open a command prompt and change directory in the jar dir and then start the jar, but I needed to double-click the jar.

+5


source


In both cases, this is the actual directory. In windows, the actual directory is automatically set to the base jar directory if you execute it from explorer. Under linux, the home directory is the actual directory for your GUI. To set a directory, write a short shell script that sets the actual directory (using the cd command) and then jars (with javaw -jar xyz.jar).



0


source







All Articles