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

Android 資料儲存(一):內部儲存的讀寫做法

編輯:關於 Android 程式設計

你可以直接把資料存進內部儲存。預設情況下,寫到內部儲存的檔案是私有的,其他應用程式無法存取;使用者卸載應用程式時,這些檔案也會一併被移除。這樣的特性讓它很適合存放不該外流的資料。

一、寫入檔案的兩種途徑

方法一:使用 Java 原生的檔案 API

FileOutputStream writeStream = null;
FileOutputStream fileOutputStream = null;
switch (view.getId()) {
    case R.id.button1:
        // 創建的文件其他程序不能訪問
        File file1 = new File(getFilesDir(), FILE1);
        try {
            // 寫入數據
            writeStream = new FileOutputStream(file1);
            writeStream.write("haha".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writeStream != null) writeStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

這裡的 getFilesDir() 會回傳應用專屬的內部目錄,比硬編碼路徑安全得多。

方法二:使用 android.content 提供的便捷方法

// 使用的是 android.content
try {
    /*
     * 設置成 MODE_PRIVATE,其他程序不能訪問。
     * 這種是默認的構造方式,可以去設置成其他的方式來使其可讀寫。
     */
    fileOutputStream = openFileOutput(FILE2, Context.MODE_PRIVATE);
    // 寫入數據
    fileOutputStream.write("hehe".getBytes());
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fileOutputStream != null) fileOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

openFileOutput() 的回報三步驟——取得串流、呼叫 write()、關閉串流——就是內部儲存寫入的標準骨架。讀檔的流程基本相同,只是把 openFileOutput() 換成 openFileInput()。

二、把靜態檔案放進 res/raw

如果要在編譯期就把一份固定檔案打包進應用,可以把它放在 res/raw/ 目錄,再以 openRawResource() 開啟。這個方法會回傳一個 InputStream,你可以從中讀取內容,但無法寫回原始檔。這個技巧在需要攜帶一份預設設定或初始資料時特別好用。

三、快取檔案

若只是想暫存一些資料而非長期保存,可用 createTempFile() 建立檔案,並以 getCacheDir() 取得存放位置。系統在內部儲存不足時可能會自行清除這些檔案,因此不該依賴它們長期存在。

四、用 adb 查看檔案

上述檔案在一般檔案總管中看不到,要確認內容得動用 adb。先列出裝置:

~$ adb devices
List of devices attached
emulator-5554   device

再進入 shell:

~$ adb -s emulator-5554 shell
#

內部儲存的目錄由應用程式的套件名決定,預設情況下其他程式無法存取;除非你明確使用了可讀或可寫的模式,否則這層隔離會一直存在。

參考資料:
https://developer.android.com/guide/topics/data/data-storage.html
https://developer.android.com/training/basics/data-storage/files.html

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