萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 檔案 I/O 完整實作:SD 卡、內部儲存、Assets 讀取

三大儲存區域存取方式

1. 外部儲存 (SD 卡/共享儲存)

需權限:READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE (API 19+ 需動態申請)。

// 檢查掛載狀態
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    File dir = new File(Environment.getExternalStorageDirectory(), "myapp");
    if (!dir.exists()) dir.mkdirs();
    File file = new File(dir, "data.txt");
    
    // 寫入
    try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write("Hello SD Card".getBytes(StandardCharsets.UTF_8));
    }
    
    // 讀取
    String content;
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buf = new byte[(int) file.length()];
        fis.read(buf);
        content = new String(buf, StandardCharsets.UTF_8);
    }
}

注意:Android 10+ (API 29) 採用分區儲存,建議改用 MediaStore 或 getExternalFilesDir() (免權限、隨 App 卸載刪除)。

2. 內部儲存 (App 專屬私有目錄)

無需權限,App 卸載自動清除。路徑:/data/data/package.name/files/

// 寫入
try (FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE)) {
    fos.write("Hello Internal".getBytes());
}

// 讀取
String content;
try (FileInputStream fis = openFileInput("data.txt")) {
    byte[] buf = new byte[fis.available()];
    fis.read(buf);
    content = new String(buf);
}

3. Assets 目錄 (唯讀、打包在 APK 內)

放置預設資料庫、字體、設定檔等唯讀資源。

// 讀取 assets/config.json
String json;
try (InputStream is = getAssets().open("config.json")) {
    byte[] buf = new byte[is.available()];
    is.read(buf);
    json = new String(buf, StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}

儲存空間資訊查詢

// 取得外部儲存總量/可用量
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSizeLong();
long totalBlocks = stat.getBlockCountLong();
long availBlocks = stat.getAvailableBlocksLong();
long totalSize = blockSize * totalBlocks;
long availSize = blockSize * availBlocks;
// 格式化顯示
String totalStr = Formatter.formatFileSize(this, totalSize);
String availStr = Formatter.formatFileSize(this, availSize);

最佳實踐建議

  1. 優先使用 Context.getFilesDir()、getCacheDir()、getExternalFilesDir() 取代硬編碼路徑。
  2. 大量 I/O 操作放入背景執行緒 (RxJava、Coroutines、ThreadPool)。
  3. 使用 try-with-resources 自動關閉流,防止洩漏。
  4. Android 10+ 遷移至分區儲存/Scoped Storage 架構。
copyright © 萬盛學電腦網 all rights reserved