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

Android 資料存取與 IO(一):SharedPreferences 與檔案讀寫

編輯:關於 Android 程式設計

任何應用都離不開資料的讀與寫。Android 提供兩條主要路徑:資料量小、結構簡單(字串、數值)時,用 SharedPreferences 存成 key-value 即可;需要大量資料與查詢能力時,則該動用資料庫。Android 內建 SQLite,並提供了便利的 API。

一、SharedPreferences:輕量級的 key-value 儲存

遊戲積分、音效與震動的開關這類設定,最適合放在 SharedPreferences。它提供的讀取方法大致有三類:

  • boolean contains(String key):判斷某個 key 是否存在。
  • Map<String, ?> getAll():一次取出全部資料。
  • getXxx(String key, xxx defValue):依型別取值,第二參數是預設值。

SharedPreferences 本身沒有寫入能力,必須先呼叫 edit() 取得 Editor:

  • putXxx(String key, xxx value):寫入一組 key-value。
  • clear():清空所有資料。
  • commit():提交修改,通常放在最後一行。

它是介面而非類別,無法直接 new,必須透過 Context 的 getSharedPreferences(String name, int mode) 取得執行個體。第二參數決定可見性:

  • MODE_PRIVATE:僅本程式可讀寫(預設值)。
  • MODE_WORLD_READABLE:其他程式可讀,不可寫。
  • MODE_WORLD_WRITEABLE:其他程式可讀可寫。

後兩者會讓任何應用都能存取你的設定檔,除少數特殊情境外不建議使用;較新的 Android 版本更已直接將它們標為不鼓勵或抛出例外。

範例:寫入與讀取按鈕

public class SharedPreferencesTest extends Activity {

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);
        editor = preferences.edit();

        Button read = (Button) findViewById(R.id.read);
        Button write = (Button) findViewById(R.id.write);

        read.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String time = preferences.getString("time", null);
                int randNum = preferences.getInt("random", 0);
                String result = (time == null)
                        ? "您暫時還未寫入數據"
                        : "寫入時間:" + time + "\n上次隨機生成的隨機數為:" + randNum;
                Toast.makeText(SharedPreferencesTest.this, result, Toast.LENGTH_LONG).show();
            }
        });

        write.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
                editor.putString("time", sdf.format(new Date()));
                editor.putInt("random", (int) (Math.random() * 100));
                editor.commit();
            }
        });
    }
}

版面檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal" >

    <Button
        android:id="@+id/write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/write" />

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/read" />
</LinearLayout>

透過 DDMS 觀察可以確認,SharedPreferences 的實體檔案存放在 /data/data/<套件名稱>/shared_prefs/ 底下,以 .xml 形式保存。

二、以 File 直接讀寫

Java 完整的 IO 體系(FileInputStream、FileOutputStream)在 Android 上一樣可用。Context 另外提供了兩個便捷方法,直接對應用程序的資料目錄操作:

  • FileInputStream openFileInput(String name)
  • FileOutputStream openFileOutput(String name, int mode)

順帶釐清一個常被搞混的概念:輸入流是從儲存裝置讀資料進記憶體,輸出流是從記憶體把資料寫到外部儲存。

mode 參數除了前述的 MODE_PRIVATE 與 MODE_WORLD_* 之外,還有一個實用的 MODE_APPEND,以附加方式開啟檔案,新內容會接在既有內容之後。

Context 也提供了幾個管理檔案目錄的方法:

  • getDir(String name, int mode):取得或建立應用資料目錄下的子資料夾。
  • getFilesDir():取得應用資料檔案的絕對路徑。
  • fileList():列出資料夾中的檔案。
  • deleteFile(String name):刪除指定檔案。

範例:兩組輸入框搭配讀寫按鈕

public class MainActivity extends Activity {

    final String FILE_NAME = "Read_Write";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button read = (Button) findViewById(R.id.read);
        Button write = (Button) findViewById(R.id.write);
        final EditText edit1 = (EditText) findViewById(R.id.edit1);
        final EditText edit2 = (EditText) findViewById(R.id.edit2);

        write.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                write(edit1.getText().toString());
                edit1.setText("");
            }
        });

        read.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                edit2.setText(read());
            }
        });
    }

    private String read() {
        try {
            FileInputStream fis = openFileInput(FILE_NAME);
            byte[] buff = new byte[1024];
            int hadRead = 0;
            StringBuilder sb = new StringBuilder();
            while ((hadRead = fis.read(buff)) > 0) {
                sb.append(new String(buff, 0, hadRead));
            }
            fis.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void write(String content) {
        try {
            FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
            PrintStream ps = new PrintStream(fos);
            ps.println(content);
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

版面檔:

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

    <Button
        android:id="@+id/write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/write" />

    <EditText
        android:id="@+id/edit1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:lines="4" />

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/read" />

    <EditText
        android:id="@+id/edit2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:lines="4"
        android:editable="false"
        android:cursorVisible="false" />
</LinearLayout>

AVD 上的執行結果:

兩種方式各有適用場景:SharedPreferences 適合少量設定,檔案IO 適合結構自由或偏大的內容;而當資料需要被查詢、排序與關聯時,就該輪到下一篇要談的 SQLite 上場了。

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