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

用 Serializable 把自訂物件存進本機:Parcelable 與 Serializable 怎麼選

編輯:關於 Android 程式設計

需要把一批自訂資料(例如使用者清單)持久化到裝置上時,Java 原生的序列化機制是最省事的方案。實作起來只要三個要素:資料類別實作 Serializable、一組 ObjectOutputStream、以及一個檔案。

先釐清:Parcelable 還是 Serializable?

兩者常被混用,但適用場景不同:

  • Parcelable:Android 專屬,效能好但要多寫一些程式碼。適合記憶體中的跨元件傳遞,例如用 Intent 在 Activity 之間搬資料。
  • Serializable:Java 標準,宣告一下就可用,速度較慢但泛用性高。適合寫入本機檔案或跨網路傳輸。

資料類別

package cc.test.serializable;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String name;

    // 強烈建議明確定義版本序號
    public static final long serialVersionUID = 9527L;

    public Student() { super(); }

    public Student(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    // getter / setter / toString 略
}

serialVersionUID 千萬別省略。一旦類別結構在版本更新中改變,而這個值又沒有固定下來,反序列化時就會直接丟 InvalidClassException,舊資料全部讀不回來。

寫入與讀出

File file = new File(Environment.getExternalStorageDirectory().toString()
        + File.separator + "Test" + File.separator + "data.dat");

if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
}
if (!file.exists()) {
    file.createNewFile();
}

// 寫入
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentsArrayList);
oos.close();
fos.close();

// 讀出
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> saved = (ArrayList<Student>) ois.readObject();
ois.close();
fis.close();

注意 ArrayList 本身已經實作 Serializable,所以只要元素型別也實作了,整個清單就能一次寫入,不必自己逐筆處理。另外檔案寫在子目錄底下時,一定要先把父目錄建出來,這是最常見的 IOException 來源。

實務上的三個提醒

第一,收尾一定要用 try/finally 或 try-with-resources 確保串流被關掉,否則檔案會殘留不完整內容,下次讀取就炸。

第二,寫入建議採「先寫暫存檔、完成後再改名覆蓋」的策略。序列化檔案一旦寫到一半被中斷(例如通話來電、低電壓關機),檔案通常就報廢了。

第三,從 Android 6.0 開始,存取外部儲存空間需要 READ/WRITE_EXTERNAL_STORAGE 執行期授權;如果不想處理權限,改用 getFilesDir() 存到應用私有目錄會乾淨許多。

版面部分完全不需要額外元件,一個 TextView 就足夠驗證:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved