【轉】在android程序中使用配置文件properties


在android程序中使用配置文件來管理一些程序的配置信息其實非常簡單

在這里我們主要就是用到Properties這個類
直接給函數給大家 這個都挺好理解的
  1. 讀寫函數分別如下:
  2. //讀取配置文件 
  3. public Properties loadConfig(Context context, String file) {
  4. Properties properties = new Properties();
  5. try {
  6. FileInputStream s = new FileInputStream(file);
  7. properties.load(s);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. return null;
  11. }
  12. return properties;
  13. }
  14. //保存配置文件
  15. public boolean saveConfig(Context context, String file, Properties properties) {
  16. try {
  17. File fil=new File(file);
  18. if(!fil.exists())
  19. fil.createNewFile();
  20. FileOutputStream s = new FileOutputStream(fil);
  21. properties.store(s, "");
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. return false;
  25. }
  26. return true;
  27. }
復制代碼
這兩個函數與Android一點關系都沒有嘛。。
所以它們一樣可以在其他標准的java程序中被使用
在Android中,比起用純字符串讀寫並自行解析,或是用xml來保存配置,
Properties顯得更簡單和直觀,因為自行解析需要大量代碼,而xml的操作又遠不及Properties方便

貼一段測試的代碼
  1. private Properties prop;
  2. public void TestProp(){
  3. boolean b=false;
  4. String s="";
  5. int i=0;
  6. prop=loadConfig(context,"/mnt/sdcard/config.properties");
  7. if(prop==null){
  8. //配置文件不存在的時候創建配置文件 初始化配置信息
  9. prop=new Properties();
  10. prop.put("bool", "yes");
  11. prop.put("string", "aaaaaaaaaaaaaaaa");
  12. prop.put("int", "110");//也可以添加基本類型數據 get時就需要強制轉換成封裝類型
  13. saveConfig(context,"/mnt/sdcard/config.properties",prop);
  14. }
  15. prop.put("bool", "no");//put方法可以直接修改配置信息,不會重復添加
  16. b=(((String)prop.get("bool")).equals("yes"))?true:false;//get出來的都是Object對象 如果是基本類型 需要用到封裝類
  17. s=(String)prop.get("string");
  18. i=Integer.parseInt((String)prop.get("int"));
  19. saveConfig(context,"/mnt/sdcard/config.properties",prop);
  20. }
復制代碼
也可以用Context的openFileInput和openFileOutput方法來讀寫文件
此時文件將被保存在 /data/data/package_name/files下,並交由系統統一管理
用此方法讀寫文件時,不能為文件指定具體路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM