Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Properties 把資料寫進檔案:Android 輕量持久化入門

編輯:Android 開發實例

Properties 可以視為一個 Hashtable 的子類,唯一的差別是:它的鍵與值都必須是字串。這個看似限制的設計,讓它能直接以「key=value」的純文字形式寫入檔案,成為 Java 世界裡最簡單的設定檔格式。

在 Android 中,Properties 通常搭配 FileInputStream / FileOutputStream 完成讀寫,適合存放少量設定型資料。

先搞懂四種檔案模式

openFileOutput() 的第二個參數決定檔案的能見度與寫入行為:

  • MODE_PRIVATE:預設值。檔案僅限本應用程式存取。
  • MODE_APPEND:若檔案已存在,資料附加到結尾,而非覆寫。
  • MODE_WORLD_READABLE:允許其他應用程式讀取。
  • MODE_WORLD_WRITEABLE:允許其他應用程式寫入。

後兩者在 API 17 起已被標記為 deprecated,並在後續版本直接拋出 SecurityException。這不是任性移除,而是安全考量:任何 App 都能讀寫的檔案等於門戶大開。跨應用程式共享資料請改用 FileProvider 或 ContentProvider。

寫入

@Override
public void onClick(View v) {
    if (v.getId() == btnlogin.getId()) {
        Properties properties = new Properties();
        String name = etname.getText().toString();
        String pwd  = etpwd.getText().toString();

        try {
            FileOutputStream out =
                    this.openFileOutput("login.cfg", Context.MODE_PRIVATE);
            properties.put("name", name);
            properties.put("pwd", pwd);
            try {
                properties.store(out, ""); // 第二個參數是註解,可留空
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        loadInfo();
    }
}

store() 的第二個參數是寫進檔案開頭的日期註解行,通常留空字串即可。實際輸出的檔案內容會像這樣:

#Wed Nov 03 12:00:00 CST 2010
name=cbin
pwd=123456

讀取

public void loadInfo() {
    Properties properties = new Properties();
    try {
        FileInputStream in = this.openFileInput("login.cfg");
        try {
            properties.load(in);
            String name = properties.get("name").toString();
            String pwd  = properties.get("pwd").toString();
            this.etname.setText(name);
            this.etpwd.setText(pwd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

這裡有個必須修正的細節:原範例用字串串接拼出 "name///" 再 setText,那是除錯殘留。正式寫法應該直接取值設定,或若要組合顯示,用 String.format 明確表達意圖。

另外 properties.get() 回傳的是 Object,若鍵不存在會得到 null,直接 toString() 將拋 NPE。較穩妥的寫法是改用 getProperty(key, defaultValue):

String name = properties.getProperty("name", "");
String pwd  = properties.getProperty("pwd", "");

別忘了關流

示範中的 FileOutputStream 與 FileInputStream 都沒有關閉。檔案描述符是有限資源,長期累積會耗盡。用 try-with-resources 一次解決:

try (FileOutputStream out =
             openFileOutput("login.cfg", Context.MODE_PRIVATE)) {
    Properties props = new Properties();
    props.setProperty("name", name);
    props.setProperty("pwd", pwd);
    props.store(out, "");
} catch (IOException e) {
    e.printStackTrace();
}

一個安全提醒

用 MODE_PRIVATE 存密碼,只是「其他 App 存取不到」,並不等於加密。在已 root 或透過備份機制取得資料的情境下,明文密碼仍會外洩。正式專案請至少做加鹽雜湊,並把長期憑證交給 Keystore 這類系統級安全儲存。

Properties 的定位

它的價值在於「零依賴、可讀、可手動編輯」,適合少量設定項。若資料有結構、需要查詢條件、或量體會成長,就該換成 SQLite;若只是零散設定值,SharedPreferences 通常比 Properties 更順手,因為它自帶向導式的型別化 API。

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