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

Android 資料持久化筆記(一):寫入內部儲存、SD 卡與權限模式

編輯:關於 Android 程式設計

開發時常需要把一些資訊保存下來。這篇整理三種把檔案寫進內部儲存與 SD 卡的做法,並比較它們的適用時機。

第一種:直接指定路徑寫檔

// Java 開發中常見的保存方式
public static boolean saveUserInfo(String username, String password) {
    File file = new File("/data/data/com.ftf.login/info.txt");
    try {
        FileOutputStream fos = new FileOutputStream(file);
        // 內容格式:ftf##123
        fos.write((username + "##" + password).getBytes());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

這種寫法把絕對路徑寫死,看起來最直接,但問題也最明顯:路徑與套件名稱綁死,專案一改 package 就失效,而且不太符合 Android 的開發慣例。

第二種:透過 Context 取得應用目錄

傳入 Context 物件,就能把檔案存進應用專屬的資料夾,這才是符合規範的做法:

public static boolean saveUserInfo(Context context, String username, String password) {
    try {
        File filesDir = context.getFilesDir();
        File file = new File(filesDir, "info.txt");
        FileOutputStream fos = new FileOutputStream(file);
        // 內容格式:ftf##123
        fos.write((username + "##" + password).getBytes());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

// 讀回資料
public static Map<String, String> getSavedUserInfo(Context context) {
    File filesDir = context.getFilesDir();
    File file = new File(filesDir, "info.txt");
    try {
        FileInputStream fis = new FileInputStream(file);
        // 使用 buffer 逐行讀
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String str = br.readLine();
        String[] infos = str.split("##");
        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;
    }
}

第三種:寫到 SD 卡

這時需要 Environment 來取得外部儲存的路徑。一般機型在 /data/data/sdcard,但部分國產手機與平板的目錄結構並非如此,用 Environment 取得可以確保相容性,也是官方推薦做法:

public static boolean saveUserInfo(Context context, String username, String password) {
    try {
        // 先確認外部儲存已掛載
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 取得 SD 卡目錄
            File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
            FileOutputStream fos = new FileOutputStream(file);
            // 內容格式:ftf##123
            fos.write((username + "##" + password).getBytes());
            fos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

注意原本寫法裡 if (...); 結尾多了一個分號,這是個很容易忽略的低階錯誤——分號讓 if 條件句提前結束,後面的程式碼永遠都會執行。另外,寫入外部儲存需要在 AndroidManifest.xml 註冊 WRITE_EXTERNAL_STORAGE 權限,而且 Android 4.4 之後外部儲存的寫入權限模型有過調整,值得留意。

第四種:用 openFileOutput 搭配權限模式

這種做法最貼近 Android 的設計思路。系統預設有四種檔案權限模式:PRIVATE(私有)、WORLD_READABLE(可讀)、WORLD_WRITEABLE(可寫)、可讀+可寫。而 Context 本身就能直接開啟檔案輸出流,不必自己拼路徑:

public static boolean saveUserInfo(Context context, String username, String password, int mode) {
    try {
        FileOutputStream fos = null;
        // 在上下文的環境中建立檔案
        switch (mode) {
            case 1:
                fos = context.openFileOutput("private.txt", Context.MODE_PRIVATE);
                break;
            case 2:
                fos = context.openFileOutput("readeable.txt", Context.MODE_WORLD_READABLE);
                break;
            case 3:
                fos = context.openFileOutput("writeable.txt", Context.MODE_WORLD_WRITEABLE);
                break;
            case 4:
                fos = context.openFileOutput("public.txt",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
                break;
        }
        // 內容格式:ftf##123
        fos.write((username + "##" + password).getBytes());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

這也是 Android 開發中保存檔案最推薦的方式:路徑由系統決定,權限由參數控制,程式碼乾淨。

最後提醒兩點。第一,範例中把帳號與密碼以「##」串接後明文存檔,這種做法在真實專案中絕對不可行——敏感資訊應該改用 EncryptedSharedPreferences 或 Keystore 加密,並避免把密碼長期存在裝置上。第二,MODE_WORLD_READABLE 與 MODE_WORLD_WRITEABLE 從 Android 4.2 起已被標記為弃用,在 Android 7.0 之後呼叫會直接拋出 SecurityException,跨應用共享檔案請改用 FileProvider。

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