Android下用Properties儲存程式配置

來源:互聯網
上載者:User

標籤:

讀寫函數分別例如以下:

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儲存程式配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.