最近研究JavaFx,有一些配置信息不知如何存儲,自己想到的方案如下
- 使用
SQLite、derby等數(shù)據(jù)庫 - 使用文件存儲,放置在
user.dir或者user.home下
以上均不是好方案java.util.prefs.Preferences提供了更好的方案
Preferences本身就是偏好的意思,平臺無關(guān)的一種方案,windows系統(tǒng)中將配置存入注冊表,類unix系統(tǒng)中存入文件系統(tǒng);
Preferences節(jié)點上可以存儲具體的配置值,也可以存儲另一個Preferences,達(dá)到樹形存儲的目的
部分API介紹
-
獲取根節(jié)點
//返回用戶的根首選項節(jié)點 Preferences preferences = Preferences.userRoot(); //返回系統(tǒng)的根首選項節(jié)點 Preferences preferences = Preferences.systemRoot(); -
獲取子節(jié)點
//返回與此節(jié)點位于同一樹中的命名首選項節(jié)點 Preferences node=preferences.node("path"); //一般會有一個應(yīng)用程序的根節(jié)點與`package`的命名類似,例如; Preferences node=preferences.node("/com/podigua"); -
獲取值
獲取值時,必須有默認(rèn)值(用戶未配置時,則會返回默認(rèn)值)
//返回各種類型的值 String str = preferences.get("str", "default string"); boolean bool = preferences.getBoolean("bool", true); byte[] bytes = preferences.getByteArray("bytes", new byte[0]); double aDouble = preferences.getDouble("double", 1.0); float aFloat = preferences.getFloat("float", 0.1f); int anInt = preferences.getInt("int", 1); long aLong = preferences.getLong("long", 1L); -
設(shè)置值
//設(shè)置各種類型的值 preferences.put("str","string"); preferences.putBoolean("bool",true); preferences.putByteArray("bytes",new byte[0]); preferences.putDouble("double",1D); preferences.putFloat("float",0.1f); preferences.putInt("int",1); preferences.putLong("long",1L); -
強(qiáng)制更改(強(qiáng)制保存配置)
//強(qiáng)制更改此首選項節(jié)點及其持久存儲的后代 preferences.flush(); -
配置的刪除
//移除配置鍵為key的配置 preferences.remove("key"); //移除當(dāng)前節(jié)點 preferences.removeNode(); -
配置的導(dǎo)入導(dǎo)出(本質(zhì)為一個xml文件)
//靜態(tài)方法導(dǎo)入一個配置 File file=new File("/option.xml"); Preferences.importPreferences(new FileInputStream(file)); //導(dǎo)出當(dāng)前節(jié)點(不含子節(jié)點) preferences.exportNode(new FileOutputStream(file)); //導(dǎo)出當(dāng)前節(jié)點以及子節(jié)點 preferences.exportSubtree(new FileOutputStream(file)); -
配置的實時生效
? 可以使用
bind或者ChangeListenerprivate SimpleStringProperty textProperty=new SimpleStringProperty(); public void start(Stage primaryStage) throws Exception{ //... Button button=new Button(); // textProperty的值發(fā)生改變時,會調(diào)整button的text button.textProperty().bind(textProperty); //... }