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

Android 資料儲存入門:內部檔案的讀與寫

編輯:關於 Android 程式設計

Android 為開發者準備了幾套資料持久化方案:檔案儲存、SharedPreferences、SQLite 資料庫,另外還可以把資料寫到外接儲存(SD 卡)。其中檔案儲存是最基礎的一種。

檔案儲存最大的特色是「不做任何格式化處理」——你寫入什麼位元組,檔案裡就是什麼內容,因此特別適合存放簡單的文字或二進位資料,例如設定草稿、快取結果、log 檔等。

一、關鍵 API

Context 類別提供了 openFileOutput() 用來寫入檔案,它接受兩個參數:

  • 檔名:注意此處不可包含路徑,因為所有檔案預設都存到 /data/data/<package>/files/ 這個 App 私有目錄下,其他應用程式無權存取。
  • 操作模式:MODE_PRIVATE 為預設值,同名檔案會被內容覆蓋;MODE_APPEND 則是若檔案已存在就附加內容,不存在才新建。

這個方法回傳 FileOutputStream,取得後就能用一般 Java I/O 串流把資料寫進去。讀取則對應 openFileInput(),只接受檔名,回傳 FileInputStream。

二、把資料寫入檔案

建立一個名為 FilePersistenceTest 的專案,先在 activity_main.xml 放一個輸入框:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="type something here" />
</LinearLayout>

接著在 Activity 被銷毀時把輸入框的內容存起來:

public class MainActivity extends Activity {

    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.edit);
    }

    public void save(String inputText) {
        FileOutputStream fileOutputStream = null;   // 檔案輸出串流
        BufferedWriter bufferedWriter = null;       // 字元緩衝串流
        try {
            fileOutputStream = openFileOutput("datafile", Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(inputText);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();         // 關流時會一併把緩衝區刷入檔案
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        save(editText.getText().toString());
    }
}

執行後在輸入框打字:

按下 Back 鍵關閉程式,內容就已落地存檔。此時可以開啟 DDMS 的 File Explorer,找到 /data/data/com.jack.filepersistencetest/files/,就會看到名為 datafile 的檔案:

點擊工具列最左側的按鈕把檔案匯出到電腦,用記事本開啟,內容如下:

可以確認輸入框裡的文字確實被保存下來了。

三、從檔案讀回資料

在 onCreate() 中呼叫 load(),把上次存下的字串還原到輸入框,並把游標移到尾端方便繼續輸入:

public String load() {
    FileInputStream in = null;      // 檔案輸入串流
    BufferedReader reader = null;   // 字元緩衝串流
    StringBuffer content = new StringBuffer();
    try {
        in = openFileInput("datafile");
        reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.edit);

    String inputText = load();
    if (!TextUtils.isEmpty(inputText)) {
        editText.setText(inputText);
        editText.setSelection(inputText.length());   // 游標移到文末
        Toast.makeText(this, "還原成功", Toast.LENGTH_SHORT).show();
    }
}

TextUtils.isEmpty() 一次就涵蓋兩種空值判斷:傳入的字串為 null 或空字串時都會回傳 true,省下分別判斷的麻煩。

重新執行,效果如下:

四、適用場景與限制

檔案儲存不適合保存結構複雜的資料。若需要查詢、排序、關聯式操作,應該改用 SQLite;若只是幾個 key-value 設定,SharedPreferences 更省事;若是大量圖片或需要對其他 App 開放的大檔,則該放進 App 專用的外接目錄 getExternalFilesDir(),並記得在 Android 6.0 以上動態申請寫入權限。更進階的持久化策略,後續再另行整理。

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