I wrote a program in Java and packaged it up as a Mac App using Netbeans. It has the typical Java, MacOS, Resources, and Plugins folders and works just fine. The problem is that my program has a save feature which, whenever used, saves files to the computer's User directory instead of the directory in which the program itself is running—the Java folder.
In the past I got around this with a custom executable containing the lines
# Set the working directory DIR=$(cd "$(dirname "$0")"; pwd) cd $DIR
But since Netbeans creates the executable now and encodes it in some unreadable way, that's not an option. I would use the old one but Netbeans adds the benefit of bundling a JRE with the program so I'm stuck having to choose between saving in the right spot or bundling the JRE.
Does anyone know how to change the working directory of a packaged program?
I took Tyler's advice and decided to find the directory I wanted within the program itself instead of trying to change the PWD with scripts.
Say you're running a Jar file by double clicking it or using terminal/cmd (This only works by directly running, not through ANT or an IDE). This will give you the directory that your Jar is in:
String path1 = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String path2 = (new File(path1)).getParentFile().getPath(); String PWD = URLDecoder.decode(path2, "UTF-8");
- The first line gets the path to your Jar file.
- The second line removes the name of the Jar from the end, leaving you with the directory it's in.
- The third line accounts for special characters like spaces.