I wrote a utility in Java that I want to eventually run as a cron job, which means I need to be able to specify the path that the code uses for its files.
There is a command line parameter that is passed to the java command that can be used to specify a particular directory, and then my java code can use that as the base path.
My command line to execute the java code is:
java -cp /Users/cwg/workspace/getInfo/bin -Duser.dir=/Users/cwg/workspace/getInfo com.cwgtech.getInfo
This will call the java code from any path, and the -Duser.dir sets the user variable to point to the path my data is stored in.
In the java code, I access the passed variable with the following code:
workingPath = System.getProperty("user.dir") + "/";
Then when I want to access a file or folder, I just pre-pend it with the workingPath String.
Node xml = loadXML(workingPath + XMLFILE);
Note: Don’t use ~ in the path for the java command, use the fully qualified path!
Also, I ended up using a couple of external Jars in my code, so I had to modify the -cp option to include the path to my lib folder as follows:
-cp /Users/cwg/workspace/getInfo/bin:/Users/cwg/workspace/getInfo/libs/*
The * at the end of the second path says to use all the jar (or zip) files in the specified folder when looking for classes. The : is the separator if you need more than one path in -classpath (can be shortened to -cp)