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

Android 按行讀取檔案內容的三種實作方式

編輯:關於 Android 程式設計

讀檔是 Android 開發的常規操作,但「怎麼讀」會直接影響效能與可讀性。以下整理三種常見寫法,分別適用於快速驗證、一般情境與長期運行的正式應用。

一、簡單版:DataInputStream

import java.io.FileInputStream;

void readFileOnLine() {
    String strFileName = "Filename.txt";
    FileInputStream fis = openFileInput(strFileName);
    StringBuffer sBuffer = new StringBuffer();
    DataInputStream dataIO = new DataInputStream(fis);
    String strLine = null;
    while ((strLine = dataIO.readLine()) != null) {
        sBuffer.append(strLine + "\n");
    }
    dataIO.close();
    fis.close();
}

程式碼最短,但 DataInputStream.readLine() 已被標記為不建議使用(deprecated):它無法正確處理編碼,遇到 UTF-8 中文容易亂碼。適合臨時測試,不建議用在正式專案。

二、簡潔版:BufferedReader

這是較通用的寫法,加上檔案存在性與例外處理:

public static String ReadTxtFile(String strFilePath) {
    String content = "";   // 檔案內容
    File file = new File(strFilePath);

    if (file.isDirectory()) {
        Log.d("TestFile", "The File doesn't not exist.");
        return content;
    }

    try {
        InputStream instream = new FileInputStream(file);
        if (instream != null) {
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;
            // 逐行讀取
            while ((line = buffreader.readLine()) != null) {
                content += line + "\n";
            }
            instream.close();
        }
    } catch (java.io.FileNotFoundException e) {
        Log.d("TestFile", "The File doesn't not exist.");
    } catch (IOException e) {
        Log.d("TestFile", e.getMessage());
    }
    return content;
}

這裡有兩個可以改進的地方:字串累加 content += line 每次都會產生新的 String 物件,檔案一大就會造成記憶體抖動,改用 StringBuilder 會好很多;另外串流關閉建議放在 finally 區塊或改用 try-with-resources,避免例外時資源洩漏。

三、正式版:適合長期運行、結構化資料

若是需要長時間執行、且檔案內容有固定格式的 App(例如本文的體重紀錄範例),建議把每一行解析成物件,並用檔案修改時間做快取,避免無效重讀。

定義資料型別

class WeightRecord {
    String timestamp;
    float weight;

    public WeightRecord(String timestamp, float weight) {
        this.timestamp = timestamp;
        this.weight = weight;
    }
}

逐行讀取並解析

private WeightRecord[] readLog() throws Exception {
    ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
    File root = Environment.getExternalStorageDirectory();
    if (root == null)
        throw new Exception("external storage dir not found");

    File weightLogFile = new File(root, WeightService.LOGFILEPATH);
    if (!weightLogFile.exists())
        throw new Exception("logfile '" + weightLogFile + "' not found");
    if (!weightLogFile.canRead())
        throw new Exception("logfile '" + weightLogFile + "' not readable");

    // 以修改時間做快取,檔案沒變就直接回傳上次結果
    long modtime = weightLogFile.lastModified();
    if (modtime == lastRecordFileModtime)
        return lastLog;
    lastRecordFileModtime = modtime;

    FileReader reader = new FileReader(weightLogFile);
    BufferedReader in = new BufferedReader(reader);
    long currentTime = -1;

    String line = in.readLine();
    while (line != null) {
        WeightRecord rec = parseLine(line);
        if (rec == null) {
            Log.e(TAG, "could not parse line: '" + line + "'");
        } else if (Long.parseLong(rec.timestamp) < currentTime) {
            Log.e(TAG, "ignoring '" + line + "' since it's older than prev log line");
        } else {
            Log.i(TAG, "line=" + rec);
            result.add(rec);
            currentTime = Long.parseLong(rec.timestamp);
        }
        line = in.readLine();
    }
    in.close();

    lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
    return lastLog;
}

// 解析每一行,格式為「時間戳;數值」
private WeightRecord parseLine(String line) {
    if (line == null) return null;
    String[] split = line.split("[;]");
    if (split.length < 2) return null;
    if (split[0].equals("Date")) return null;   // 跳過表頭
    try {
        String timestamp = split[0];
        float weight = Float.parseFloat(split[1]);
        return new WeightRecord(timestamp, weight);
    } catch (Exception e) {
        Log.e(TAG, "Invalid format in line '" + line + "'");
        return null;
    }
}

寫入檔案

public boolean logWeight(Intent batteryChangeIntent) {
    Log.i(TAG, "logBattery");
    if (batteryChangeIntent == null) return false;

    try {
        FileWriter out = null;
        if (mWeightLogFile != null) {
            try {
                out = new FileWriter(mWeightLogFile, true);
            } catch (Exception e) { }
        }

        if (out == null) {
            File root = Environment.getExternalStorageDirectory();
            if (root == null)
                throw new Exception("external storage dir not found");

            mWeightLogFile = new File(root, WeightService.LOGFILEPATH);
            boolean fileExists = mWeightLogFile.exists();

            if (!fileExists) {
                if (!mWeightLogFile.getParentFile().mkdirs()) {
                    Toast.makeText(this, "create file failed", Toast.LENGTH_SHORT).show();
                }
                mWeightLogFile.createNewFile();
            }
            if (!mWeightLogFile.exists())
                throw new Exception("creation of file '" + mWeightLogFile + "' failed");
            if (!mWeightLogFile.canWrite())
                throw new Exception("file '" + mWeightLogFile + "' is not writable");

            out = new FileWriter(mWeightLogFile, true);
            if (!fileExists) {
                out.write(createHeadLine());
                out.write('\n');
            }
        }

        String extras = createBatteryInfoLine(batteryChangeIntent);
        out.write(extras);
        out.write('\n');
        out.flush();
        out.close();
        return true;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return false;
    }
}

選擇建議

臨時測試用第一種即可;一般文字檔用第二種並記得改用 StringBuilder;需要長期穩定運行的正式應用走第三種,加上快取與格式驗證,並記得檔案 I/O 屬耗時操作,應放在背景執行緒執行。另外,Android 10(API 29)起分區儲存已成預設,直接寫入 Environment.getExternalStorageDirectory() 會受限,建議改用 App 專用目錄 getExternalFilesDir() 或 MediaStore API。

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