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

Android 資料儲存入門:SharedPreferences、內部檔案與 Assets

編輯:Android 程式設計入門

這一課把 Android 最基礎的三種資料儲存方式一次做完:SharedPreferences 存鍵值對、內部儲存空間讀寫文字檔、以及把 Assets 中的圖片複製到 App 私有目錄後顯示。

版面配置

畫面上有兩組「儲存/讀取」按鈕分別對應 SharedPreferences 與文字檔,一組「儲存檔案/讀取檔案」處理圖片,最後用 ImageView 呈現結果。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hanqi.test5.DataActivity1"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_1"
        android:hint="key"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_2"
        android:hint="value"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存"
            android:layout_weight="1"
            android:onClick="bt1_OnClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取"
            android:layout_weight="1"
            android:onClick="bt2_OnClick"/>
    </LinearLayout>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_3"
        android:hint="要存儲的內容"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_4"
        android:hint="從文件中讀取的內容"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存"
            android:layout_weight="1"
            android:onClick="bt3_OnClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取"
            android:layout_weight="1"
            android:onClick="bt4_OnClick"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="保存文件"
            android:layout_weight="1"
            android:onClick="bt5_OnClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="讀取文件"
            android:layout_weight="1"
            android:onClick="bt6_OnClick"/>
    </LinearLayout>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/vipflower"
        android:id="@+id/iv_4"/>
</LinearLayout>

SharedPreferences:鍵值對的輕量儲存

適合存設定、標記、上一次的登入帳號這類小片段資料。取得實例時就指定檔名與存取模式:

sp = getSharedPreferences("mydata", MODE_PRIVATE);

寫入透過 Editor,最後一定要 commit() 才會落地:

public void bt1_OnClick(View v) {
    String key = et_1.getText().toString();
    String value = et_2.getText().toString();
    if (key.length() == 0 || value.length() == 0) {
        Toast.makeText(DataActivity1.this, "key 或 value 不能為空", Toast.LENGTH_SHORT).show();
    } else {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        boolean b = editor.commit();
        Toast.makeText(DataActivity1.this, b ? "保存成功" : "保存失敗", Toast.LENGTH_SHORT).show();
    }
}

讀取時帶入預設值,找不到 key 時就不會拿到 null:

public void bt2_OnClick(View v) {
    String key = et_1.getText().toString();
    et_2.setText(sp.getString(key, "沒有發現 key"));
}

內部儲存:讀寫文字檔

openFileOutput() 與 openFileInput() 會自動把檔案放進 App 的私有目錄,其他應用程式無法存取。這裡用 MODE_APPEND 做到「追加」而非覆寫:

final String FILENAME = "test.txt";

public void bt3_OnClick(View v) {
    String content = et_3.getText().toString();
    try {
        FileOutputStream fos_1 = openFileOutput(FILENAME, MODE_APPEND);
        PrintStream pm = new PrintStream(fos_1);
        pm.println(content);
        pm.close();
        fos_1.close();
        Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
    }
}

public void bt4_OnClick(View v) {
    try {
        FileInputStream fis = openFileInput(FILENAME);
        byte[] b = new byte[1024];
        int i = 0;
        StringBuilder sb_1 = new StringBuilder();
        while ((i = fis.read(b)) > 0) {
            sb_1.append(new String(b, 0, i));
        }
        fis.close();
        et_4.setText(sb_1);
        Toast.makeText(DataActivity1.this, "讀取成功", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(DataActivity1.this, "讀取失敗", Toast.LENGTH_SHORT).show();
    }
}

Assets 與私有目錄之間的檔案搬運

assets 目錄裡的檔案是唯讀的,若要讓 ImageView 直接指向它並不方便,常見做法是先用串流複製一份到 getFilesDir() 底下:

public void bt5_OnClick(View v) {
    AssetManager am = getAssets();
    try {
        InputStream is = am.open("yuantu.png");
        FileOutputStream fos = openFileOutput("yuantu.png", MODE_PRIVATE);
        byte[] b = new byte[1024];
        int i = 0;
        while ((i = is.read(b)) > 0) {
            fos.write(b, 0, i);
        }
        fos.close();
        is.close();
        Toast.makeText(DataActivity1.this, "保存成功", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(DataActivity1.this, "保存失敗", Toast.LENGTH_SHORT).show();
    }
}

讀取時組出絕對路徑,用 BitmapFactory 解碼後塞給 ImageView:

public void bt6_OnClick(View v) {
    String filepath = getFilesDir().getAbsolutePath();
    filepath += "/yuantu.png";
    Bitmap bm = BitmapFactory.decodeFile(filepath);
    iv_4.setImageBitmap(bm);
}

三種方式怎麼選

SharedPreferences 體積最小、讀寫最快,適合少量結構化設定;內部檔案適合較長的文字或自訂格式資料;assets 則是打包在 APK 內的唯讀資源,需要修改就得先複製出來。資料量大、需要查詢條件時,才需要再往 SQLite 或 ORM 框架邁進。

資料儲存體系總覽:

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