Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Properties 檔取代 SharedPreferences 保存設定

編輯:關於 Android 程式設計

SharedPreferences 存在 /data/data/包名/ 之下,走的是應用私有儲存空間。它的優點是 API 簡單、讀取快,但資料會佔用內部空間;當你要存的是大量資料或希望設定檔能直接被外部工具讀寫,它就顯得侷促。這種時候,用 Java 標準的 Properties 類別搭配一個檔案路徑,反而更靈活。

基本思路

繼承 Properties,記住自己的檔案路徑,然後在寫入的時候順手存檔。因為 Properties 本身就是一個 Map,讀取時完全照原樣使用即可,不需要額外包裝。

package com.nil.cache;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesConfig extends Properties {

    private String propertyPath = "";

    private PropertiesConfig(String path) {
        this.propertyPath = path;
    }

    public static PropertiesConfig getInstance(String path) {
        File file = new File(path);

        // 檔案不存在時建立它(注意條件是「不存在」,不是「存在」)
        if (!file.exists()) {
            try {
                File parent = file.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        PropertiesConfig pro = new PropertiesConfig(path);
        try {
            InputStream is = new FileInputStream(file);
            pro.load(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pro;
    }

    @Override
    public synchronized Object setProperty(String key, String value) {
        super.setProperty(key, value);
        this.store();
        return value;
    }

    public synchronized Object put(String key, String value) {
        super.put(key, value);
        this.store();
        return value;
    }

    private void store() {
        try {
            this.store(new FileOutputStream(this.propertyPath), "utf-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

怎麼用

// 寫入
PropertiesConfig.getInstance("/sdcard/client_config.xml").setProperty("187", "name");

// 讀取(第二個參數是找不到 key 時的預設值,不傳會得到 null)
String value = PropertiesConfig.getInstance("/sdcard/client_config.xml")
        .getProperty("187", "");

幾點修正與提醒

原始範例中的檔案判斷寫成了 if (file.exists()) 才去 createNewFile(),邏輯正好相反,導致檔案永遠不會被建立。上面已修正為 !file.exists(),並補上父目錄建立,避免寫到 SD 卡某個尚不存在的子目錄時失敗。

另外要留意三件事。第一,Properties 的 load 與 store 預設使用 ISO-8859-1 編碼,中文容易亂碼;在 API 9 以上請改用 load(Reader) 與 store(Writer, comment) 並明確指定 UTF-8。第二,這個實作在每次寫入時都整檔重寫,適合「偶爾改幾個設定」,不適合高頻寫入。第三,存取 /sdcard 需要 WRITE_EXTERNAL_STORAGE 權限與執行期授權,而且該路徑在 Android 4.4 之後屬於共享儲存,任何有權限的 App 都能讀到——不要把權杖、密碼這類敏感資料放在這裡,那些仍應留在 getFilesDir() 或EncryptedSharedPreferences 中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved