Monday, October 7, 2013

Store and retrieve preference with java.util.prefs package

The java.util.prefs package provides a way for applications to store and retrieve user and system preference and configuration data. The data is stored persistently in an implementation-dependent backing store. ~ reference: Core Java™ Preferences API

Simple example using Preferences:

package javapreferences;

import java.util.prefs.Preferences;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaPreferences {
    
    static final String KeyWeb = "KEY_WEB";
    static final String KeyInt = "KEY_INT";
    static final String KeyBoolean = "KEY_BOOLEAN";

    public static void main(String[] args) {
        Preferences preferences = Preferences.userRoot().node("java-buddy");
        
        String prefWeb = preferences.get(KeyWeb, "");
        int prefInt = preferences.getInt(KeyInt, 0);
        boolean prefBoolean = preferences.getBoolean(KeyBoolean, false);
        
        System.out.println("Stored KEY_WEB: " + prefWeb);
        System.out.println("Stored KEY_INT: " + prefInt);
        System.out.println("Stored KEY_BOOLEAN: " + prefBoolean);
        
        System.out.println("Save something to Preferences");
        preferences.put(KeyWeb, "http://java-buddy.blogspot.com/");
        preferences.putInt(KeyInt, 1234567890);
        preferences.putBoolean(KeyBoolean, true);
    }
}


Simple example using Preferences
Simple example using Preferences

No comments:

Post a Comment