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

Android 內部存儲的文件讀寫:以使用者資訊保存為例

編輯:關於 Android 程式設計

相對於 SharedPreferences 只能存鍵值對,直接操作檔案更適合保存使用者帳號、設定快照或稍具結構的資料。context.getFilesDir() 指向應用私有的 files 目錄,不需要任何權限,卸載時也會一併清除,是最安全的起點。

保存資料

public static boolean saveUserInfo(Context context, String username, String password) {
    try {
        // 定義一個檔案路徑物件
        File file = new File(context.getFilesDir(), "info.txt");
        // 定義檔案的寫入流
        FileOutputStream fos = new FileOutputStream(file);
        // 用自訂分隔符把兩段資料寫入同一行
        fos.write((username + "##" + password).getBytes());
        // 關閉寫入流
        fos.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

讀取資料

public static Map<String, String> getSavedUserInfo(Context context) {
    try {
        // 定義一個檔案路徑物件
        File file = new File(context.getFilesDir(), "info.txt");
        // 定義檔案讀取流
        FileInputStream fis = new FileInputStream(file);
        // 包裝成按行讀取的 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        // 讀取文本檔案中的一行資料
        String string = br.readLine();
        // 以分隔符切開字串
        String[] infos = string.split("##");
        // 封裝成 Map 回傳
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", infos[0]);
        map.put("password", infos[1]);
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

這段範例的重點在於「自訂分隔符 + 單行存放」的簡易序列化手法,寫得少也讀得快。但要留意三個問題:一是若使用者名稱本身含有 ##,切分就會出錯;二是 split() 的參數是規則運算式,井號雖非保留字元,若換成「.」「|」這類符號必須自行轉義;三是密碼以純文字存在檔案中並不安全,正式專案請改用 SharedPreferences 搭配 EncryptedSharedPreferences,或至少做過雜湊處理,切勿沿用這種明文做法。

另外,讀寫檔案屬於 I/O 操作,不該放在主執行緒,檔案稍大就會觸發 ANR 甚至 StrictMode 警告,建議一律放到背景執行緒,完成後再回主執行緒更新介面。

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