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

Android 文件讀寫的兩種方式對比

編輯:關於 Android 程式設計

方式一:把文件當作資源放在 res 目錄下

把 txt 文件放進 res/raw 或 assets 目錄,是很多教程會提到的做法。兩者的讀取方式略有不同:

// res/raw 下的文件,可以直接通過 R 文件拿到資源 ID
InputStream is = getResources().openRawResource(R.raw.fileName);

// assets 下的文件,通過 AssetManager 打開
AssetManager am = getAssets();
InputStream is2 = am.open("FileName");

raw 與 assets 的區別在於:raw 會在 R 文件中生成資源 ID,便於引用;assets 不會生成 ID,只能靠字符串路徑訪問,好處是可以建立任意深度的子目錄結構。

但這種方式有一個致命限制:只讀,不能寫。這些文件打包在 apk 裡,apk 安裝後是只讀的,任何寫入嘗試都會失敗。所以需要動態保存數據時,必須換用第二種方式。

方式二:從外部存儲讀寫文件

先在 AndroidManifest.xml 中加入權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

然後把文件操作封裝到一個獨立的類裡,這裡命名為 FileOption:

package com.example.littleapplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.Vector;

import android.os.Environment;
import android.util.Log;

public class FileOption {

    private String fileName;
    private File targetFile;
    private File sdCardDir;

    public FileOption(String fileName) throws IOException {
        // 先判斷外部存儲是否已掛載
        boolean mark = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (mark) {
            this.fileName = fileName;
            this.sdCardDir = Environment.getExternalStorageDirectory();
            this.targetFile = new File(this.sdCardDir.getCanonicalPath() + this.fileName);
            if (this.targetFile.exists() == false) {
                this.targetFile.createNewFile();
            }
        } else {
            Log.e("FileOption", "無內存卡");
        }
    }

    /** 逐行讀取,返回所有行 */
    public Vector<String> read() throws FileNotFoundException, IOException {
        FileInputStream fis = new FileInputStream(
                this.sdCardDir.getCanonicalPath() + this.fileName);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        Vector<String> res = new Vector<String>();
        String line = null;
        while ((line = br.readLine()) != null) {
            res.add(line);
        }
        br.close();
        return res;
    }

    /** 追加寫入一行 */
    public boolean write(String add) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(this.targetFile, "rw");
        raf.seek(targetFile.length());   // 指針移到末尾,實現追加
        raf.write(add.getBytes());
        raf.writeChar('\n');             // 換行
        raf.close();
        return true;
    }

    /**
     * 返回一共有多少條記錄
     * 約定每 5 行代表一個數據項,分別是 id、title、content、data、level
     */
    public int size() throws FileNotFoundException, IOException {
        FileInputStream fis = new FileInputStream(
                this.sdCardDir.getCanonicalPath() + this.fileName);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String line = null;
        int count = 0;
        while ((line = br.readLine()) != null) {
            count++;
        }
        br.close();
        return count / 5;
    }
}

代碼裡的幾處要點

構造時先判斷掛載狀態。外部存儲可能處於未掛載、被移除或僅充電模式,這時任何文件操作都會失敗,必須提前攔截。

RandomAccessFile 實現追加。seek(targetFile.length()) 把指針定位到文件末尾,寫入的內容自然接在原內容之後。這是實現「日誌式追加」最直接的方式。

原稿中的兩處筆誤已修正。一是 write 方法裡的 raf.writeChar(' ') 原本想表達換行,但空格並不能換行,應改為 '\n';二是 Log.e 的第一個參數原本寫成了未定義的 SDK,已改為類名標籤。

路徑拼接建議改用 File 構造函數。new File(dir, fileName) 比字符串相加更安全,能自動處理分隔符,也不容易在 dir 末尾恰好帶斜線時拼出雙斜線。

現代 Android 上的取捨

這份封裝的結構思路(判斷狀態、封裝讀寫、統計條數)至今仍然適用,但存儲位置需要調整:

  • 如果數據只給自己的應用使用,應該存到 getFilesDir()(內部存儲)或 getExternalFilesDir()(外部私有目錄),不需要任何存儲權限,卸载時自動清除。
  • 如果要讓用戶能直接看到並管理文件,Android 10 以後應使用 MediaStore 或 SAF,直接拼絕對路徑的寫法已受限。
  • 如果只是保存少量鍵值數據,SharedPreferences 更合適;結構化數據則直接用 SQLite 或 Room,不必自己發明「每 5 行一條記錄」的文本格式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved