萬盛學電腦網

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

Android 將 Assets 資源檔案複製到 SD 卡完整實作教學

應用場景

當 App 需要在首次啟動時將預置的資源檔(如資料庫、字體、配置檔)從 assets 目錄釋放到外部儲存(SD 卡)供後續讀寫,常用此技術。本文提供一個健壯的遞歸複製工具類,支援斷點續傳與錯誤處理。

核心複製邏輯

/**
 * 將 assets 目錄下所有檔案(排除指定資料夾)複製到目標路徑
 *
 * @param context      上下文
 * @param targetDir    目標目錄 File 物件
 * @param excludeDirs  需排除的資料夾名稱陣列(如 "images", "sounds")
 */
public static void copyAssetsToSdCard(Context context, File targetDir, String... excludeDirs) {
    // 1. 確保目標目錄存在
    if (!targetDir.exists() && !targetDir.mkdirs()) {
        Log.e("AssetCopy", "無法建立目標目錄:" + targetDir.getAbsolutePath());
        return;
    }

    // 2. 取得 assets 根目錄檔案列表
    String[] assetsList;
    try {
        assetsList = context.getAssets().list("");
    } catch (IOException e) {
        Log.e("AssetCopy", "讀取 assets 列表失敗", e);
        return;
    }

    // 3. 轉換排除列表為 Set 提升查找效能
    Set<String> excludeSet = new HashSet<>(Arrays.asList(excludeDirs));

    // 4. 遍歷複製
    for (String fileName : assetsList) {
        if (excludeSet.contains(fileName)) continue; // 跳過排除資料夾

        File outFile = new File(targetDir, fileName);
        if (outFile.exists()) continue; // 已存在則跳過(斷點續傳)

        copySingleAsset(context, fileName, outFile);
    }
}

/** 單檔複製輔助方法 */
private static void copySingleAsset(Context context, String assetPath, File outFile) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = context.getAssets().open(assetPath);
        out = new FileOutputStream(outFile);
        byte[] buffer = new byte[4096];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
    } catch (IOException e) {
        Log.e("AssetCopy", "複製檔案失敗:" + assetPath, e);
        // 刪除不完整檔案
        if (outFile.exists()) outFile.delete();
    } finally {
        closeQuietly(in);
        closeQuietly(out);
    }
}

/** 安全關閉流 */
private static void closeQuietly(Closeable c) {
    if (c != null) try { c.close(); } catch (IOException ignored) {}
}

使用範例

// 在 Application 或首頁 Activity 的 onCreate 中呼叫
File sdDir = new File(Environment.getExternalStorageDirectory(), "MyAppData");
copyAssetsToSdCard(this, sdDir, "images", "sounds", "webkit");

關鍵點解析

  • 非同步執行:複製大量檔案會阻塞主執行緒,建議放入 Thread、AsyncTask 或 RxJava 背景執行緒。
  • 權限宣告:Android 10 (API 29) 以上需 MANAGE_EXTERNAL_STORAGE 或使用 MediaStore / getExternalFilesDir() 替代公開 SD 卡路徑。
  • 進度回調:可擴充介面回報複製進度,配合 ProgressBar 提升用戶體驗。
  • 錯誤恢復:捕獲 IOException 並刪除損壞檔案,避免下次啟動誤以為已複製完成。

現代替代方案

針對唯讀資源(如資料庫、JSON),直接使用 context.getAssets().open() 讀取即可,無需複製。若確實需寫入,優先使用 getExternalFilesDir(null) 取得應用專屬目錄,免權限且隨應用卸載自動清理。

copyright © 萬盛學電腦網 all rights reserved