fuin.org

Small Open Source Java Tools and Libraries

Properties file preferences

Shows the use of a directory and properties file based Preferences API External link implementation. It's basically a replacement for the registry based implementation on Windows.
        // Create an application wide preferences directory 
        // named "config" in the current startup directory
        final File systemPrefDir = new File("./config");
        if (!systemPrefDir.exists()) {
            systemPrefDir.mkdir();
        }

        // Create a user preferences directory with your 
        // applications name in the user's home directory
        final File userHomeDir = new File(System.getProperty("user.home"));
        final File userPrefDir = new File(userHomeDir, ".myapp");
        if (!userPrefDir.exists()) {
            userPrefDir.mkdir();
        }

        // Set both directories as system properties
        System.setProperty(PropertiesFilePreferencesFactory.SYSTEM_PREF_DIR, 
                           systemPrefDir.toString());
        System.setProperty(PropertiesFilePreferencesFactory.USER_PREF_DIR, 
                           userPrefDir.toString());

        // Set the factory
        System.setProperty("java.util.prefs.PreferencesFactory",
                PropertiesFilePreferencesFactory.class.getName());

        // Write something to the preferences
        final Preferences userPrefs = Preferences.userRoot();
        userPrefs.putInt("a", 1);
        userPrefs.put("b", "test");
        
A file ${user.home}/.myapp/preferences.properties will be created:
        
# DO NOT EDIT!
# Created by org.fuin.utils4j.PropertiesFilePreferences
# yyyy-MM-dd HH:mm:ss
a=1
b=test

You can find a full example here Internal link outside layout (Package "org.fuin.examples.utils4j").