May 15, 2010

Reading plist files

When developing for the mac platform, app preferences are supposed to be stored in ~/Library/Preferences/.  While finding and reading a preference file is easy enough, reading usable information from it is another matter.  This is because in the last couple of system updates (10.5+) the xml based plist files used for preferences are now saved in a binary format, not the UTF-8 format you would suspect.  The tricky part of this is that if you are using the NSDictonary class in Objective-C you will not encounter any problems, but when using any other programing language you suddenly get a mess of garbage text.  Luckily OSX had a built in command to help remedy the issue.  The plutil command converts plists between the text based XML and binary based.

As an example in Java you can use the Runtime class to invoke the command on the fly.

Runtime.getRuntime().exec(new String[]{plutil", "-convert", "xml1", filepath});

To convert a file back once you have read or edited it use this.
Runtime.getRuntime().exec(new String[]{plutil", "-convert", "binary1", filepath});

It is also good check for the lastIndexOf("bplist") as it will alert you if the file is currently in binary form.