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

Android 第 7 課:資料儲存總覽與檔案讀寫的實作細節

編輯:關於 Android 程式設計

程式處理完的資料要留到下次執行,就得靠儲存機制。Android 提供了五種主要方式:

  • 檔案(File)
  • SharedPreferences
  • SQLite 資料庫
  • 內容提供者(ContentProvider)
  • 網路

這一課先把最基礎的「檔案」講透,後面幾課再逐一拆解其他方案。

順帶釐清一個常見誤解:許多人把 ROM 當成唯讀儲存,但這裡討論的儲存位置是應用可讀寫的資料區;真正用來放程式與唯讀資源的分割區,才是不能隨意寫入的。

寫入:openFileOutput()

Activity 直接提供了 openFileOutput(),用法與 J2SE 寫檔幾乎一致:

public class FileActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FileOutputStream outStream =
                this.openFileOutput("itcast.txt", Context.MODE_PRIVATE);
        outStream.write("趙雅智部落格".getBytes());
        outStream.close();
    }
}

第一個參數:檔名

只能給檔名,不能包含路徑分隔符「/」。檔案不存在時 Android 會自動建立。實際存放位置為:

/data/data/<package name>/files/

例如 /data/data/cn.itcast.action/files/itcast.txt。想確認檔案有沒有真的產生,可以在 Eclipse 中開啟「Window」→「Show View」→「Other」,展開 Android 資料夾選擇「File Explorer」,再展開上述目錄即可看到。

第二個參數:操作模式

四種模式與對應的常數值:

Context.MODE_PRIVATE          = 0
Context.MODE_APPEND           = 32768
Context.MODE_WORLD_READABLE   = 1
Context.MODE_WORLD_WRITEABLE  = 2
  • MODE_PRIVATE:預設模式。檔案私有,僅應用本身可存取,寫入會覆蓋原內容。
  • MODE_APPEND:檢查檔案是否存在,存在就追加內容,不存在則建立新檔。
  • MODE_WORLD_READABLE:允許其他應用讀取此檔。
  • MODE_WORLD_WRITEABLE:允許其他應用寫入此檔。

若要同時開放讀與寫,把兩個常數相加:

openFileOutput("itcast.txt",
        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

為什麼預設是私有的

Android 有一套自己的安全模型:應用程式(.apk)安裝時,系統會指派一個專屬的 user id;當應用要存取檔案等資源時,需要 user id 相符才放行。

因此,任何應用建立的檔案、SharedPreferences 與資料庫,預設都屬於私有(位於 /data/data/<package name>/files),其他程式無法存取。只有在建立時明確指定 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE,別人才讀得到。

讀取:openFileInput()

FileInputStream inStream = this.getContext().openFileInput("itcast.txt");
Log.i("FileTest", readInStream(inStream));

把串流轉成字串的輔助方法:

public static String readInStream(FileInputStream inStream) {
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, length);
        }
        outStream.close();
        inStream.close();
        return outStream.toString();
    } catch (IOException e) {
        Log.i("FileTest", e.getMessage());
    }
    return null;
}

也可以用絕對路徑直接開檔:

File file = new File("/data/data/cn.itcast.action/files/itcast.txt");
FileInputStream inStream = new FileInputStream(file);
Log.i("FileTest", readInStream(inStream));

注意路徑中的 cn.itcast.action 是應用所屬套件,實作時要換成自己程式的套件名。私有檔案只能由建立它的應用存取。

兩個取得目錄的便捷方法

  • getCacheDir():取得 /data/data/<package name>/cache,適合放暫存檔,系統空間不足時可能會清除。
  • getFilesDir():取得 /data/data/<package name>/files,適合放需要長期保留的檔案。

完整範例:把登入帳密存進檔案

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.lession02_login"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.lession02_login.LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

版面配置

<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:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/view_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_name" />

        <EditText
            android:id="@+id/edit_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" >
            <requestFocus />
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/view_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_pass" />

        <EditText
            android:id="@+id/edit_pass"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPassword" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

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

        <CheckBox
            android:id="@+id/check_remember"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="@string/login_remember" />
    </LinearLayout>

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">lession02_login</string>
    <string name="login_name">使用者名稱</string>
    <string name="login_pass">密碼</string>
    <string name="login_login">登入</string>
    <string name="login_remember">記住密碼</string>
</resources>

串流轉字串工具:StreamTools.java

package com.example.lession02_login.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class StreamTools {

    public static String getValue(FileInputStream fis) throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = fis.read(buffer)) != -1) {
            stream.write(buffer, 0, length);
        }
        stream.flush();
        stream.close();

        return stream.toString();
    }
}

業務層:LoginService.java

寫入時用 MODE_APPEND,這樣每次登入都會在檔案後方累加一筆;若改用 MODE_PRIVATE 則只會保留最後一筆。讀取時以冒號切分還原成 key-value。

package com.example.lession02_login.service;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

import com.example.lession02_login.util.StreamTools;

import android.content.Context;

public class LoginService {

    private Context context;

    public LoginService(Context context) {
        super();
        this.context = context;
    }

    /**
     * 把使用者名稱與密碼寫入應用私有檔案
     */
    public boolean saveToRom(String name, String pass, String fileName) {
        try {
            // MODE_PRIVATE:僅應用本身可存取,內容會被覆蓋
            // FileOutputStream fos = context.openFileOutput(
            //         fileName, Context.MODE_PRIVATE);

            // MODE_APPEND:在既有內容後追加
            FileOutputStream fos = context.openFileOutput(
                    fileName, Context.MODE_APPEND);

            String result = name + ":" + pass;
            fos.write(result.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 讀取檔案並還原為 Map
     */
    public Map<String, String> readFile(String fileName) {
        Map<String, String> map = null;
        try {
            FileInputStream fis = context.openFileInput(fileName);
            String value = StreamTools.getValue(fis);
            String values[] = value.split(":");

            if (values.length > 0) {
                map = new HashMap<String, String>();
                map.put("name", values[0]);
                map.put("pass", values[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

界面層:LoginActivity.java

package com.example.lession02_login;

import java.util.Map;

import com.example.lession02_login.service.LoginService;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private EditText edit_name, edit_pass;
    private Button btn_login;
    private Checkable box_remember;
    private LoginService loginService;

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

        loginService = new LoginService(this);

        edit_name = (EditText) findViewById(R.id.edit_name);
        edit_pass = (EditText) findViewById(R.id.edit_pass);
        btn_login = (Button) findViewById(R.id.button_login);
        box_remember = (Checkable) findViewById(R.id.check_remember);

        btn_login.setOnClickListener(new MyOnclickListener());

        // 回顯上次儲存的資料
        Map<String, String> map = loginService.readFile("append.txt");
        if (map != null) {
            edit_name.setText(map.get("name"));
            edit_pass.setText(map.get("pass"));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    class MyOnclickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_login:
                    String name = edit_name.getText().toString();
                    String pass = edit_pass.getText().toString();

                    if (TextUtils.isEmpty(name)) {
                        Toast.makeText(LoginActivity.this, "使用者名稱不可為空",
                                Toast.LENGTH_LONG).show();
                        return;
                    } else if (TextUtils.isEmpty(pass)) {
                        Toast.makeText(LoginActivity.this, "密碼不可為空",
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (box_remember.isChecked()) {
                        loginService.saveToRom(name, pass, "append.txt");
                        Toast.makeText(LoginActivity.this, "儲存使用者名稱與密碼",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "不儲存使用者名稱與密碼",
                                Toast.LENGTH_LONG).show();
                    }
                    break;

                default:
                    break;
            }
        }
    }
}

補充:看懂 ls -l 的權限位

在 File Explorer 或 shell 中看檔案,會看到類似 -rw-rw---- 的字串:

  • 最前面一位:D 代表目錄,- 代表檔案。
  • 後面九位分成三組,每組三位:R 可讀、W 可寫、X 可執行。
  • 前三組代表擁有者(当前使用者)、中三組代表所屬群組、後三組代表其他人(全域)。

重點整理

  • openFileOutput() 只收檔名,檔案固定落在 /data/data/<package name>/files/。
  • 預設 MODE_PRIVATE 最安全;要累加用 MODE_APPEND;MODE_WORLD_* 兩個模式在後續版本已不建議使用。
  • 讀檔用 openFileInput(),搭配 ByteArrayOutputStream 緩衝區把串流轉字串。
  • 把檔案邏輯抽到 Service、把串流處理抽到工具類,Activity 只留 UI 邏輯,後續換成 SP 或 SQLite 才好維護。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved