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

Android 讀寫私有檔案的函數實作

編輯:進階開發

在 Android 中,應用程式可以將資料以私有檔案的形式儲存在自己的專用空間裡。透過 openFileInput() 與 openFileOutput(),讀寫這類檔案變得相當容易。以下提供一組可直接參考的讀寫函數。

讀取私有檔案

public String ReadSettings(Context context) {
    FileInputStream fIn = null;
    InputStreamReader isr = null;
    char[] inputBuffer = new char[255];
    String data = null;
    try {
        fIn = openFileInput("lee.txt");
        isr = new InputStreamReader(fIn);
        isr.read(inputBuffer);
        data = new String(inputBuffer);
        Toast.makeText(context, "Settings read", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(context, "Settings not read", Toast.LENGTH_SHORT).show();
    } finally {
        try {
            isr.close();
            fIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return data;
}

寫入私有檔案

public void WriteSettings(String data) {
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;
    try {
        fOut = openFileOutput("lee.txt", MODE_PRIVATE);
        osw = new OutputStreamWriter(fOut);
        osw.write(data);
        osw.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            osw.close();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

重點說明

  • 讀取時以 openFileInput() 開啟檔案輸入流,並用 InputStreamReader 讀入字元。
  • 寫入時以 openFileOutput("lee.txt", MODE_PRIVATE) 開啟輸出流,MODE_PRIVATE 表示檔案僅供本應用存取。
  • 兩個方法都使用 try-catch-finally 結構,確保在 finally 中妥善關閉串流,避免資源洩漏。

這組函數結構清楚、可直接套用,適合用在儲存應用的小型設定資料。實際使用時,可依資料量調整緩衝區大小,並補上更完善的例外處理。

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