當 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 背景執行緒。MANAGE_EXTERNAL_STORAGE 或使用 MediaStore / getExternalFilesDir() 替代公開 SD 卡路徑。IOException 並刪除損壞檔案,避免下次啟動誤以為已複製完成。針對唯讀資源(如資料庫、JSON),直接使用 context.getAssets().open() 讀取即可,無需複製。若確實需寫入,優先使用 getExternalFilesDir(null) 取得應用專屬目錄,免權限且隨應用卸載自動清理。