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

Android/Java 檔案讀寫:二進位與文字檔的實用範式

編輯:關於 Android 程式設計

檔案讀寫是基礎但反覆用到的能力。這裡整理四個實用的方法:讀取媒體檔的位元組串流、讀取文字檔、寫入位元組、寫入文字。

一、讀取媒體檔為 byte[]

讀取圖片、影片等二進位檔案時,用 ByteArrayOutputStream 承接串流內容,最後一次轉為陣列。

public static byte[] readStream(String imagepath) throws Exception {
    FileInputStream fs = new FileInputStream(imagepath);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while (-1 != (len = fs.read(buffer))) {
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    fs.close();
    return outStream.toByteArray();
}

這個寫法有個實務問題:整個檔案都被載入記憶體。讀取大型媒體檔時極易 OOM。若後續用途是顯示圖片,應改用 BitmapFactory.decodeFile() 搭配 inSampleSize 降採樣;若用途是上傳,則應直接串流處理,不必先落地成 byte[]。

二、讀取文字檔為 String

public String readFile(String filename) {
    String content = null;
    File file = new File(filename);
    try {
        FileReader reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

這裡有個隱患:file.length() 回傳的是位元組數,而 char 陣列需要的是字元數。若檔案含中文等多位元組編碼,兩者不相等,會導致讀取結果被截斷或尾部出現亂碼。穩妥的寫法是用 StringBuilder 迴圈讀取:

public String readFile(String filename) {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(filename), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try { reader.close(); } catch (IOException e) { /* ignore */ }
        }
    }
    return sb.toString();
}

明確指定編碼也很重要。FileReader 會使用平台預設編碼,在不同裝置上可能不一致。

三、寫入媒體檔(必須用 byte[])

public void writeFile(String filePath, byte[] f) {
    try {
        FileOutputStream out = new FileOutputStream(new File(filePath));
        out.write(f);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、寫入文字檔

寫 log 或純文字內容時用這個版本:

public void writeFile(String filePath, String f) {
    FileWriter fw = null;
    try {
        fw = new FileWriter(filePath);
        fw.write(f);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fw != null) {
            try { fw.close(); } catch (IOException e) { /* ignore */ }
        }
    }
}

五、幾個通用要點

一律用 finally 或 try-with-resources 關檔。上面四個範例原本的寫法在異常發生時不會關閉串流,長時間運行會耗盡檔案描述符。若專案的 minSdk 已達 19 以上,直接用 try-with-resources 最乾淨:

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    // ...
}

外部儲存需要權限與存在性檢查。寫入 SD 卡前應先確認掛載狀態:

if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    // 外部儲存不可用,走降級方案
}

同時在 manifest 中加入 WRITE_EXTERNAL_STORAGE;Android 6.0 之後還需要 runtime permission 申請流程。

寫檔前確保父目錄存在。new FileOutputStream() 遇到不存在的路徑會拋 FileNotFoundException,而這個例外訊息同時涵蓋「路徑不存在」與「無權限」兩種情況,排查時容易誤判。事先呼叫 file.getParentFile().mkdirs() 可省下不少時間。

寫檔的原子性。若檔案內容不容許寫到一半就中斷(例如設定檔),建議先寫入暫存檔,成功後再用 renameTo() 覆蓋目標檔。這樣即使中途斷電或進程被殺,原檔案仍然完整。

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