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

Android 檔案存取實戰:私有目錄與公用儲存空間

編輯:關於 Android 程式設計

Android 檔案儲存的基本概念

Android 的檔案存取通常可分為私有目錄與公用儲存空間。私有目錄屬於特定應用,卸載後通常會被清除;公用儲存空間則可讓使用者或其他應用存取,例如舊稱 SD 卡的外部儲存空間。

私有目錄

私有目錄常用於保存應用內部資料,例如設定檔、暫存檔或資料庫。常見路徑概念如下:

  • cache 目錄:適合暫存資料,系統在空間不足時可能清除。
  • files 目錄:適合保存應用需要持續使用的檔案。

私有檔案可透過 openFileInput 與 openFileOutput 讀寫。openFileOutput 的第二個參數可指定寫入模式,例如 MODE_PRIVATE 會覆蓋原內容,MODE_APPEND 則會附加內容。

Java File 類別常用建構方式

  • File(File dir, String name):指定目錄物件與檔名。
  • File(String path):直接指定完整路徑。
  • File(String dirPath, String name):指定目錄路徑與檔名。

將 assets 檔案寫入私有目錄

以下範例示範如何從 assets 讀取文字檔,再寫入應用私有目錄。

FileInputStream input = null;
FileOutputStream output = null;

try {
    input = getResources().getAssets().open(fileName);
    output = openFileOutput(fileName, Context.MODE_PRIVATE);

    byte[] buffer = new byte[1024];
    int len;

    while ((len = input.read(buffer)) != -1) {
        output.write(buffer, 0, len);
    }

    output.flush();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

讀取私有文字檔

FileInputStream input = null;

try {
    input = openFileInput(fileName);
    byte[] buffer = new byte[input.available()];
    input.read(buffer);

    String content = new String(buffer).trim();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

將圖片儲存到私有目錄

若來源是圖片,可先將 InputStream 轉為 Bitmap,再透過 compress 輸出。

InputStream input = null;
FileOutputStream output = null;

try {
    input = getResources().getAssets().open(fileName);
    output = openFileOutput(fileName, Context.MODE_PRIVATE);

    Bitmap bitmap = BitmapFactory.decodeStream(input);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

公用儲存空間

若要將檔案存到公用儲存空間,通常需要先確認外部儲存是否已掛載,再建立對應目錄與檔案。以下為簡化範例。

boolean isExternalStorageMounted() {
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}

void saveTextToPublicStorage(String content) {
    if (!isExternalStorageMounted()) {
        return;
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "MyApp");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, "note.txt");

    try {
        FileOutputStream output = new FileOutputStream(file);
        output.write(content.getBytes());
        output.flush();
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

存取公用圖片

void saveBitmapToPublicStorage(Bitmap bitmap) {
    if (!isExternalStorageMounted()) {
        return;
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "MyApp");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File file = new File(dir, "photo.jpg");

    try {
        FileOutputStream output = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
        output.flush();
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

小結

Android 檔案存取需要釐清私有目錄與公用儲存空間的差異。私有目錄適合應用內部資料,公用儲存則適合需要對外分享或由使用者瀏覽的檔案。實作時應注意檔案是否存在、串流是否確實關閉,以及外部儲存是否可用。

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