Preferences Stores Per User Settings

Persist small settings with the Preferences API: type-aware putters, safe getters with defaults, and an explicit flush to force the backing store.

JavaConfig Management

Code

snippet
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public class SettingsStore {

    public static void main(String[] args) throws BackingStoreException {
        // 按类的包名定位用户偏好节点:/devexamples/settings
        Preferences prefs = Preferences.userNodeForPackage(SettingsStore.class);

        // 类型化写入:键上限 80 字符、值上限 8192 字符
        prefs.put("theme", "dark");
        prefs.putInt("recentFiles", 8);
        prefs.putBoolean("autoSave", true);

        // 显式 flush 强制落盘;JVM 正常退出也会保住未刷写的更新
        prefs.flush();

        System.out.println("theme: " + prefs.get("theme", "light"));
        System.out.println("recentFiles: " + prefs.getInt("recentFiles", 3));
        System.out.println("autoSave: " + prefs.getBoolean("autoSave", false));

        // get 带默认值兜底:键缺失或后端不可访问都返回默认
        System.out.println("missing key: " + prefs.get("nonexistent", "(unset)"));

        // keys() 列出本节点全部键;remove 删除单个键
        for (String key : prefs.keys()) {
            System.out.println("stored: " + key + "=" + prefs.get(key, ""));
        }
        prefs.remove("recentFiles");
        prefs.flush();
        System.out.println("after remove: " + prefs.getInt("recentFiles", 0));
    }
}

What the file does

The working surface is the class SettingsStore — everything else is wiring.

One loop does the cycling here: for (String key : prefs.keys()).

Caveats

  • No external surface — the standard library supplies all behavior.

Putting it to use

Look for the theme:, recentFiles:, autoSave: labels once the file executes; the labels pair lines with steps.

The central lines

Preferences prefs = Preferences.userNodeForPackage(SettingsStore.class);
prefs.putBoolean("autoSave", true);
prefs.putInt("recentFiles", 8);

Interactive Tools for This Topic

FAQ

What does Preferences Stores Per User Settings print when run?
Execute the whole file; each printed line is prefixed with a label like `theme:`, `recentFiles:`, `autoSave:`.