Table of Contents

Preferences

User Preferences

You need to store keys and values that are both strings, for a specific user, with platform independence.

Example

PreferencesTest/PreferencesTest.java

package PreferencesTest;
 
import java.util.prefs.Preferences;
 
public class PreferencesTest{
	Preferences prefs;
 
	public PreferencesTest(){
		System.out.println("Creating new PreferencesTest object...");
		prefs = Preferences.userNodeForPackage(PreferencesTest.class);
 
		loadPrefs();
	}
 
	private void loadPrefs(){
		System.out.println("Loading preferences...");
 
		// retrieve some preferences previously stored, with defaults
		// in case this is the first run
		String text = prefs.get("textFontName", "lucida-bright");
		String display = prefs.get("displayFontName", "lucida-blackletter");
		System.out.println("text: " + text);
		System.out.println("display: " + display);
 
		// assume the user chose new preference values: store them back
		prefs.put("textFontName", "times-roman");
		prefs.put("displayFontName", "helvetica");
	}
 
	public static void main(String[] args){
		PreferencesTest pt = new PreferencesTest();
	}
}

After running the program, the following is created or updated if it already exists (Mac OSX Example): ~/Library/Preferences/com.apple.java.util.prefs.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>/</key>
	<dict>
		<key>PreferencesTest/</key>
		<dict>
			<key>displayFontName</key>
			<string>helvetica</string>
			<key>textFontName</key>
			<string>times-roman</string>
		</dict>
	</dict>
</dict>
</plist>