Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 檔案讀寫:封裝一個可重複使用的 FileIOHelper 工具類

編輯:初階開發

檔案讀寫是很日常的需求,與其每次重寫一遍,不如包成一個輔助類。以下這個 FileIOHelper 就是這樣誕生的,往後直接拿去用即可。

一、定義檔案與串流

public class FileIOHelper {

    Context context;
    File file;
    FileInputStream fin;
    FileOutputStream fout;

    public FileIOHelper(Context c, String name, String path) throws IOException {
        context = c;
        file = new File(path, name);
        file.createNewFile();
        fin = new FileInputStream(file);
        fout = new FileOutputStream(file);
    }
}

建構子接收 Context、檔名與路徑,確保檔案存在後,同時開啟輸入與輸出串流。

二、寫入

public void write(String s) throws IOException {
    fout.write(s.getBytes());
    fout.close();
}

三、讀取

public byte[] read(int s, int l) throws IOException {
    byte[] save = new byte[l];
    fin.read(save, s, l);
    return save;
}

四、編碼轉換

public String encode(byte[] array) {
    return EncodingUtils.getString(array, TEXT_ENCODING);
}

五、取得檔案長度

public int length() {
    return (int) file.length();
}

六、實際使用

public class FileIOUsage extends Activity {

    public final static String NAME = "griffinshi.txt";
    public final static String PATH = "data/data/com.android.FileIO";

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

        try {
            FileIOHelper helper = new FileIOHelper(this, NAME, PATH);

            String string = "Hello to Gryphone!";
            helper.write(string);

            byte[] array = helper.read(0, helper.length());
            String data = helper.encode(array);

            TextView tv = new TextView(this);
            tv.setText(data);
            setContentView(tv);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

執行後畫面上會顯示剛剛寫入的內容,形成一個最簡單的「寫入再讀回」驗證。

七、這個版本還有哪些問題

不支援追加。原實作每次都用 new FileOutputStream(file) 開檔,這會把原內容整個清空,因此只能整份覆寫。若需要追加,建構 FileOutputStream 時要傳第二個參數 true:new FileOutputStream(file, true)。

串流同時開著。建構子裡把 fin 與 fout 一起開啟,實際上大部分情境只需要其中一個。而且寫入後關掉 fout、讀取後也該關掉 fin,否則檔案會被佔用。

沒有 flush。寫入後直接 close 通常沒問題,但若中途需要讀回同一份內容,務必先 flush() 再讀,否則可能讀到舊資料。

路徑寫死。範例把路徑硬編碼成 data/data/com.android.FileIO,這在真机上很可能因權限而失敗。正確做法是用 getFilesDir() 取得應用私有目錄,例如:

File file = new File(context.getFilesDir(), "griffinshi.txt");

這樣路徑會自動指向 /data/data/<你的套件名>/files,不必也不能自行猜測。

read 的返回值未檢查。fin.read(save, s, l) 實際讀到的位元組數可能小於 l(尤其讀到檔尾時),應該用回傳值來決定有效長度,否則 byte 陣列尾端會是一堆 0。

建議改用 try-with-resources。Java 7 之後可以這樣寫,自動關閉串流並把例外處理收斂乾淨:

try (FileInputStream in = new FileInputStream(file)) {
    byte[] data = in.readAllBytes();
    return new String(data, StandardCharsets.UTF_8);
}

八、確認檔案真的產生了

用 adb 進 shell 查看:

$ adb shell
# cd data
# cd com.android.FileIO
# ls
griffinshi.txt
lib

看到 griffinshi.txt 出現在清單中,就代表寫入成功。若要在自己的電腦上直接看內容,可以 adb pull 把檔案拉回本機;不過新版 Android 對 /data/data 的存取已大幅收緊,非 root 環境下通常需要用 run-as 套件名 才能進入應用私有目錄。

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