【问题标题】:How do I save preference user settings in Java?如何在 Java 中保存首选项用户设置?
【发布时间】:2011-04-30 08:23:27
【问题描述】:

例如,我有一个带有首选项按钮的窗口。 I want to make it so that when user press the preference button and checks his/her appropriate options and press ok, it saves the preference, then when user presses run on the main window, it runs accordingly to preference the user changed on the preference窗口。

提前谢谢你。

【问题讨论】:

  • 你的意思是网页的行为会根据偏好而改变吗?将首选项保存在数据库表中。

标签: java swing jframe jbutton


【解决方案1】:

您可以使用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"

还有更多examples at java2s.com。

【讨论】:

  • 示例仓库链接已失效。
  • 我知道这是一个非常古老的答案,但希望得到答复。我想问一下我是否有 100 多个设置数据,这是最好的方法还是可能有其他方法,比如存储在文件中?
  • @Aman 你真的有 100+ 的设置数据吗?这没有多大意义。但无论如何。首选项用于存储少量数据。100+ 还可以
【解决方案2】:

有一个Java Preferences API 专门用于此目的。它允许您以一种简单的跨平台方式存储每个用户的偏好,而 API 本身负责存储数据的位置和方式。

【讨论】:

    【解决方案3】:

    除了首选项之外,还有另一种可供使用Java Web Start 启动的富客户端使用的选项。这种替代方案是 PersistenceService。这是一个小的demo. of the PersistenceService。

    这也是一种服务,程序员无需担心信息存储在哪里的细节。

    【讨论】:

      【解决方案4】:
      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("YOUR_TARGET_FILE_PATH");
              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 来保存您的偏好

      【讨论】:

      • 我知道这已经有 2 年历史了,但并不是每个人都使用 Microsoft Windows 计算机,而且大多数人都将C: 设置为默认驱动器,甚至更少安装了E: 驱动器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      相关资源
      最近更新 更多