Android下用Properties儲存程式配置

來源:互聯網
上載者:User
讀寫函數分別如下:

import java.io.FileInputStream;<br />import java.io.FileOutputStream;<br />import java.util.Properties;</p><p>public Properties loadConfig(Context context, String file) {<br />Properties properties = new Properties();<br />try {<br />FileInputStream s = new FileInputStream(file);<br />properties.load(s);<br />} catch (Exception e) {<br />e.printStackTrace();<br />}<br />return properties;<br />}</p><p>public void saveConfig(Context context, String file, Properties properties) {<br />try {<br />FileOutputStream s = new FileOutputStream(file, false);<br />properties.store(s, "");<br />} catch (Exception e){<br />e.printStackTrace();<br />}<br />}
orz,是不是發現什麼了?對了,這兩個函數與Android一點關係都沒有嘛。。
所以它們一樣可以在其他標準的java程式中被使用
在Android中,比起用純字串讀寫並自行解析,或是用xml來儲存配置,
Properties顯得更簡單和直觀,因為自行解析需要大量代碼,而xml的操作又遠不及Properties方便

使用方法如下:
寫入配置:
Properties prop = new Properties();<br />prop.put("prop1", "abc");<br />prop.put("prop2", 1);<br />prop.put("prop3", 3.14);<br />saveConfig(this, "/sdcard/config.dat", prop);
讀取配置:
Properties prop = loadConfig(this, "/sdcard/config.dat");<br />String prop1 = prop.get("prop1");
註:也可以用Context的openFileInput和openFileOutput方法來讀寫檔案
此時檔案將被儲存在 /data/data/package_name/files下,並交由系統統一管理
用此方法讀寫檔案時,不能為檔案指定具體路徑。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.