標籤:
讀寫函數分別例如以下:
import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;public Properties loadConfig(Context context, String file) {Properties properties = new Properties();try {FileInputStream s = new FileInputStream(file);properties.load(s);} catch (Exception e) {e.printStackTrace();}return properties;}public void saveConfig(Context context, String file, Properties properties) {try {FileOutputStream s = new FileOutputStream(file, false);properties.store(s, "");} catch (Exception e){e.printStackTrace();}}
orz,是不是發現什麼了?對了,這兩個函數與Android一點關係都沒有嘛。。
所以它們一樣能夠在其它標準的java程式中被使用
在Android中,比起用純字串讀寫並自行解析,或是用xml來儲存配置,
Properties顯得更簡單和直觀,由於自行解析須要大量代碼,而xml的操作又遠不及Properties方便
用法例如以下:
寫入配置:
Properties prop = new Properties();prop.put("prop1", "abc");prop.put("prop2", 1);prop.put("prop3", 3.14);saveConfig(this, "/sdcard/config.dat", prop);
讀取配置:
Properties prop = loadConfig(this, "/sdcard/config.dat");String prop1 = prop.get("prop1");
註:也能夠用Context的openFileInput和openFileOutput方法來讀寫檔案
此時檔案將被儲存在 /data/data/package_name/files下,並交由系統統一管理
用此方法讀寫檔案時,不能為檔案指定詳細路徑。
Android下用Properties儲存程式配置