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

Android 內部儲存讀寫檔案實作教學

編輯:關於 Android 程式設計

實務開發裡,「把一個檔案寫進手機」幾乎是必備技能。要談寫檔,先把儲存空間的輪廓交代清楚。

零、儲存空間的分類

內部儲存空間

• RAM:執行用的記憶體,等同電腦的記憶體。
• ROM/內部儲存:長期保存資料的空間,等同電腦的硬碟。

外部儲存空間

• 可插拔的 SD 卡(或模擬的外部私有目錄),相當於行動硬碟、隨身碟。

本文示範如何在「內部儲存」中讀寫檔案。

一、範例:登入畫面記住帳密

幾乎每個帶登入介面的 App 都需要把使用者資訊存到本機,就用這個最經典的場景來演練。

版面配置如下:

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

    <EditText
        android:id="@+id/ed_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名"
        android:layout_margin="20dp" />

    <EditText
        android:id="@+id/ed_passwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:inputType="textPassword"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="40dp"
            android:text="自動登錄" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="40dp"
            android:onClick="login"
            android:text="登錄" />
    </RelativeLayout>
</LinearLayout>

二、寫入檔案

按下登入鈕時,若勾選了自動登入,就把帳密寫到應用包名下的 info.txt。

public void login(View v) {
    String name = ed_name.getText().toString();
    String passwd = ed_passwd.getText().toString();

    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(passwd)) {
        Toast.makeText(this, "用戶名或密碼不能為空", Toast.LENGTH_SHORT).show();
        return;
    }

    if (cb.isChecked()) {
        File file = new File(getFilesDir(), "info.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            // 以 name##passwd 的格式寫入
            fos.write((name + "##" + passwd).getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try { fos.close(); } catch (IOException e) { }
            }
        }
    }
    Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();
}

把檔案拉出來看,內容就是我們寫入的字串。

三、讀取檔案

進入 Activity 時,如果檔案存在就讀出來回填。

public void readInfo() {
    File file = new File(getFilesDir(), "info.txt");
    if (!file.exists()) return;

    BufferedReader buffer = null;
    try {
        FileInputStream fin = new FileInputStream(file);
        // 位元組流轉字元流,再包一層緩衝
        buffer = new BufferedReader(new InputStreamReader(fin));
        String text = buffer.readLine();
        String[] s = text.split("##");
        ed_name.setText(s[0]);
        ed_passwd.setText(s[1]);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (buffer != null) {
            try { buffer.close(); } catch (IOException e) { }
        }
    }
}

四、別再手寫路徑:用 API 取得目錄

上面那種把 /data/data/com.demo.storage/ 硬寫在程式碼裡的做法很危險——打錯一個字母就全盤失效,而且換個包名就報錯。Google 提供了兩個標準 API:

• getFilesDir():回傳 /data/data/你的包名/files,適合放需要長期保存的檔案。
• getCacheDir():回傳 /data/data/你的包名/cache,適合放暫存檔,系統空間不足時會自行清除。

// 舊寫法(不建議)
// File file = new File("/data/data/com.demo.storage/info.txt");

// 標準寫法:getFilesDir() 回傳 File 物件
File file = new File(getFilesDir(), "info.txt");

若想確認實際位置,可到「設定 → 應用程式 → 執行中」找到該進程檢視。

其中的 Clear Data 會清掉整個包名目錄下的內容,Clear Cache 只清 cache 資料夾。理解這兩個按鈕的作用範圍,除錯時判斷「資料為什麼不見了」會快很多。

五、小結

內部儲存的優點是應用私有、不需任何權限、卸载才會消失;缺點是容量有限且無法讓使用者直接瀏覽。若需要較大檔案或對外分享,就該轉往外部儲存,並記得處理權限與掛載狀態判斷。

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