Android下使用Properties文件保存程序設置

    廢話不說,直接上代碼。
    讀取.properties文件中的配置: 

  1. String strValue = ""
  2. Properties props = new Properties(); 
  3. try { 
  4.     props.load(context.openFileInput("config.properties")); 
  5.     strValue = props.getProperty (keyName); 
  6.     System.out.println(keyName + " "+strValue); 
  7. catch (FileNotFoundException e) { 
  8.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
  9. catch (IOException e) { 
  10.     Log.e(LOG_TAG, "config.properties IO Exception",e); 

    相信上面這段代碼大部分朋友都能看懂,所以就不做過多的解釋了。

    向.properties文件中寫入配置:

  1. Properties props = new Properties(); 
  2. try { 
  3.     props.load(context.openFileInput("config.properties")); 
  4.     OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE); 
  5.     Enumeration<?> e = props.propertyNames(); 
  6.     if(e.hasMoreElements()){ 
  7.         while (e.hasMoreElements()) { 
  8.             String s = (String) e.nextElement(); 
  9.             if (!s.equals(keyName)) { 
  10.                 props.setProperty(s, props.getProperty(s)); 
  11.             } 
  12.         } 
  13.     } 
  14.     props.setProperty(keyName, keyValue); 
  15.     props.store(out, null); 
  16.     String value = props.getProperty(keyName); 
  17.     System.out.println(keyName + " "+value); 
  18. catch (FileNotFoundException e) { 
  19.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
  20. catch (IOException e) { 
  21.     Log.e(LOG_TAG, "config.properties IO Exception",e); 

    上面這段代碼,跟讀取的代碼相比,多了一個if判斷以及一個while循環。主要是因爲Context.Mode造成的。因爲我的工程涉及到多個配置信息。所以只能是先將所有的配置信息讀取出來,然後在寫入配置文件中。
    Context.Mode的含義如下:
    1.MODE_PRIVATE:爲默認操作模式,代表該文件是私有數據,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原文件的內容。
    2.MODE_APPEND:代表該文件是私有數據,只能被應用本身訪問,該模式會檢查文件是否存在,存在就往文件追加內容,否則就創建新文件。
    3.MODE_WORLD_READABLE:表示當前文件可以被其他應用讀取。
    4.MODE_WORLD_WRITEABLE:表示當前文件可以被其他應用寫入。

    注:.properties文件放置的路徑爲/data/data/packagename/files
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章