Search code examples
javajardirectoryexecute

Run .jar with Specific. path


I want to run from an diffrent dicrectory a .jar when i use java -jar PATH_TO_FILE it will be executed in the directory where i run the command. How can I say, that the jar will be start in the directory where the .jar located.


Solution

  • You can't; not with a command line switch, at any rate. You have 3 broad strategies to fix whatever ailment this causes:

    Fix your bugs

    Evidently, your application is written with the presumption that the 'current working directory' is whereever the jar file. This is a common bug in java code that needs access to e.g. a png image file for rendering in e.g. a GUI, or parse a txt file with some static information.

    The fix is to not write that code in the first place - the proper mechanism for storing read-only resources with your app is to put them the same place classes are put: Inside jars, by your build system. Put them in src/main/resources (assuming you're using maven or something that works similarly), and use YourClass.class.getResource("open.png") to read them, not new File.

    Stop using the place your jar lives as datastore

    Alternatively, if it's read/write files, those shouldn't live where your jar files live: That is a windowsism, and an early 90s windowsism at that: Users should not be presumed to have write access to the place where executables live. The right place for such files are somewhere in the user's home directory (probably a subdir of that), which you can ask for in java with System.getProperty("user.home").

    Write a script

    If you must, write a batch script or shell script that does it. There are many ways in posix (so, linux, mac os, etc) to fire off a process in another directory. PowerShell scripts on windows can accomplish similar tasks. This is ugly (and OS dependent), so the first 2 options are much better.