如何在Java中保存首选项用户设置?

例如,我有一个首选button的窗口。 我想这样做,当用户按下首选项button并检查他/她的适当的选项,然后按确定,它将保存首选项,然后当用户按下主窗口上运行时,它会相应地运行,以优先用户更改首选项窗口。

先谢谢你。

你可以使用java.util.prefs包。 一个简单的例子:

// Retrieve the user preference node for the package com.mycompany Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class); // Preference key name final String PREF_NAME = "name_of_preference"; // Set the value of the preference String newValue = "a string"; prefs.put(PREF_NAME, newValue); // Get the value of the preference; // default value is returned if the preference does not exist String defaultValue = "default string"; String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string" 

在java2s.com有更多的例子 。

有一个Java首选项API专门用于此目的。 它允许您以简单的跨平台方式存储每个用户的偏好设置,而API本身则负责在哪里以及如何存储数据。

除了“首选项”之外,还有另一种可用于使用Java Web Start启动的胖客户端的选项。 这个替代scheme是PersistenceService。 这是一个小的演示。 的PersistenceService 。

这也是程序员不需要担心信息存储位置的细节。

 public void saveProperties() { try { String USER_NAME = "Some name"; String DP_ADDRESS = "Some url"; //create a properties file Properties props = new Properties(); props.setProperty("User name", USER_NAME); props.setProperty("Display picture address", DP_ADDRESS); File f = new File("E://user.properties"); OutputStream out = new FileOutputStream( f ); //If you wish to make some comments props.store(out, "User properties"); } catch (Exception e ) { e.printStackTrace(); } } 

您可以使用java.util.Properties来保存您的首选项