import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; public class Test { public static void main(String[] args){ PreferencesDemo.test(); } } /* 这里用的是userNodeForPackage(),但是我们也可以选择用systemNodeForPackage; 虽然可以任意选择,但是最好使用“user”用于个别用户的偏好,用“system”用于通用的安 装配置。因为main是静态的,因此PreferencesDemo.class可以用来表示节点,但是非静 态的方法内部,我们通常使用getClass(),尽管我们不一定非要把当前的类作为节点标识符 ,但这任不失为一种很有用的方法。 ——不明所以 数据储存在哪了?在程序第一次运行之后,并没有垂涎任何本地文件。Preferences API利 用合适的系统资源完成这个任务,并且这些资源会随着操作系统的不同而不同。例如在 Windows系统里,就利用注册表(因为它已经有了“键值对”这样的节点对层次结构了)。但是 最重要的一点是,它已经神奇般地为我们储存了信息,所以我们不必担心不同的操作系统怎么 运作的 */ class PreferencesDemo { public static void test() { Preferences prefs = Preferences.userNodeForPackage(Test.class); prefs.put("Location", "Oz"); prefs.put("Location", "Ruby Slippers"); prefs.putInt("Companions", 4); prefs.putBoolean("Are there witches?", true); //典型的用法 int usageCount = prefs.getInt("UsageCount", 0); usageCount++; prefs.putInt("UsageCount", usageCount); try { for (String key : prefs.keys()) { System.out.println(key + ":" + prefs.get(key, null)); } System.out.println("How many companions does Dorothy have?"); System.out.println(prefs.getInt("Companions", 0)); } catch (BackingStoreException e) { e.printStackTrace(); } } }