Search code examples
javajarcross-platformsettingspreferences

Where to store preferences in a Java application?


I need just a solution to retrieve a path for storing desktop application settings (e.g. a sqlite database) that meets following needs:

  • cross platform
  • works from jar and from "normal" invocation

I've spent a lot of time googling and experimenting with getting the codebase path via X.class.getProtectionDomain().getCodeSource().getLocation() and java.util.pref.Preferences class, but return values gave sometimes different results, returned null or just "/" as path.

"Cross Platform" is kind of hard to define. A solution called "best practice for each platform" won't be easy to achieve. Making a difference between user-specific and shared data would be sensible.


Solution

  • java.util.prefs.Preferences is the proper way to do it. It works perfectly fine (I've used it in a desktop application without any problems). It is cross-platform and is available without any extra jars. It also differentiates between user-specific and global data. Perhaps shed some light on your particular problems with it (or ask another question)

    Of course, you can use java.util.Properties as well, and store files in System.getProperty("user.dir").