Question

According to the Java Info.plist Key Reference for Mac, you're supposed to be able to use the $APP_PACKAGE variable to be able to access the root directory of a Mac Application bundle. So I figure that I can store a file in the Contents/Resources/ folder and access it by calling

new File("$APP_PACKAGE/Contents/Resources/MyFile.txt")

However, this doesn't seem to work and I simply get a file not found error. Moreover, I've tried the following to see if I could narrow down the problem:

new File("$APP_PACKAGE/Contents").exists() //Returns false
System.out.printline(new File("$APP_PACKAGE").getParent()) //Returns an empty string

I did generate the Mac OS X bundle using Eclipse's Export to Mac OS X application bundle, if that matters. Any help (or a suitable workaround) would be greatly appreciated!

Was it helpful?

Solution

I figured it out! Even though the app had a hard time telling me what the working directory is, I managed to figure out that it is the folder that the application is in. Then I was able to solve it by referring to the app as a directory:

new File("MyApp.app/Contents/Resources/MyFile.txt").exists() //Returns true!!!

I'd also like to add that I found the suggestion on this blog post to add the following to my info.plist file:

<key>WorkingDirectory</key>
<string>$APP_PACKAGE/Contents/Resources</string>

Unfortunately, this doesn't seem to work on Mac OS 10.7.5 and the working directory just gets reset to the folder that the application is in.

OTHER TIPS

If the value is set as as an environment variable, you may use System.getEnv() to first get the actual value of APP_PACKAGE then create the File object using it.

String appPackage = System.getEnv("APP_PACKAGE");
new File(appPackage + "/Contents/Resources/MyFile.txt");

That said, from the reading of your given link I wonder if this variable is just expended while read from the plist file, not in your Java process. If the variable is not actually given as an environment variable to your Java program, you can retrieve your file in the Contents directory easily since as I remember the packaging of an app on Mac should have the following architecture

/Contents
  /MacOS
    YourBinary
  /Resources
    YourFile.txt

Depending on the current working directory of your app (I think it should default to /Contents/MacOS) you can retrieve the correct path using ../Resources/YourFile.txt. If you don't know the current working directory you can print the value of new File(".").getAbsolutePath()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top