Java中的Preferences的基本使用方法:
import java.util.prefs.Preferences;
public class PreferencesDemo {
public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(PreferencesDemo.class);
prefs.put("Location", "Oz");
prefs.put("Footwear", "Ruby Slippers");
prefs.putInt("Companions", 4);
prefs.putBoolean("Are there witches?", true);
int usageCount = prefs.getInt("UsageCount", 0);
usageCount++;
prefs.putInt("UsageCount", usageCount);
for (String key : prefs.keys()) {
System.out.println(key + ": " + prefs.get(key, null));
}
// You must always provide a default value:
System.out.println("How many companions does Dorothy have? " + prefs.getInt("Companions", 0));
}
}
import java.util.prefs.Preferences;
public class PreferencesDemo {
public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(PreferencesDemo.class);
prefs.put("Location", "Oz");
prefs.put("Footwear", "Ruby Slippers");
prefs.putInt("Companions", 4);
prefs.putBoolean("Are there witches?", true);
int usageCount = prefs.getInt("UsageCount", 0);
usageCount++;
prefs.putInt("UsageCount", usageCount);
for (String key : prefs.keys()) {
System.out.println(key + ": " + prefs.get(key, null));
}
// You must always provide a default value:
System.out.println("How many companions does Dorothy have? " + prefs.getInt("Companions", 0));
}
}
1. import
2.
3. public class
4. public static
void main(String[] args) throws
5. Preferences prefs = Preferences.userNodeForPackage(PreferencesDemo.class);
6. prefs.put("Location", "Oz");
7. prefs.put("Footwear", "Ruby Slippers");
8. prefs.putInt("Companions", 4);
9. prefs.putBoolean("Are there witches?",
true);
10. int usageCount = prefs.getInt("UsageCount",
0);
11. usageCount++;
12. prefs.putInt("UsageCount", usageCount);
13. for
14. System.out.println(key + ": " + prefs.get(key,
null));
15. }
16. // You must always provide a default value:
17. System.out.println("How many companions does Dorothy have? " + prefs.getInt("Companions",
0));
18. }
19. }
代码来自:《Thinking in Java》
详细使用,请参考对应的JDK文档!=^_^=