首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 讀取 Assets 資源完整指南:AssetManager 正確用法

     編輯:程式設計綜合問答

Android 專案的 assets/ 目錄適合存放原始檔案(JSON、字體、資料庫、HTML 等),這些檔案編譯時不會生成 R.id,必須透過 AssetManager 以串流方式讀取。常見錯誤包括嘗試用 File 類別直接開啟(會拋出 FileNotFoundException)或在非 Context 類別中直接呼叫 getAssets()。

正確讀取步驟

1. 取得 AssetManager 實例

在 Activity、Service、Application 或任何持有 Context 的類別中:

AssetManager assetManager = context.getAssets(); // 或 this.getAssets()

2. 開啟輸入串流

InputStream inputStream = assetManager.open("helloworld.txt"); // 檔案相對 assets/ 路徑

3. 讀取內容(文字檔範例)

InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr);
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    content.append(line).append("\n");
}
reader.close();
// content.toString() 即為完整檔案內容

完整工具類範例

public class AssetUtils {
    public static String readTextFile(Context context, String fileName) {
        try (InputStream is = context.getAssets().open(fileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
            return sb.toString();
        } catch (IOException e) {
            Log.e("AssetUtils", "Read asset failed: " + fileName, e);
            return null;
        }
    }

    public static List readLines(Context context, String fileName) {
        String content = readTextFile(context, fileName);
        if (content == null) return Collections.emptyList();
        return Arrays.asList(content.split("\\r?\\n"));
    }
}

常見坑與注意事項

  • 路徑不包含 assets/:open("data/config.json") 對應 assets/data/config.json。
  • 子目錄支援:assets/fonts/ 下的檔案用 open("fonts/Roboto.ttf")。
  • 不可寫入:Assets 唯讀,若需修改請先複製到內部儲存(context.getFilesDir())。
  • 大檔案分塊讀取:超過 1MB 檔案建議使用 InputStream 逐塊處理,避免一次載入全部記憶體。
  • 編碼指定:明確指定 StandardCharsets.UTF_8,避免中文亂碼。

進階:列出目錄內所有檔案

String[] files = assetManager.list("configs"); // 回傳 assets/configs/ 下的檔名陣列
for (String file : files) {
    Log.d("Assets", "Found: " + file);
}

掌握 AssetManager 正確用法,即可靈活處理各類原始資源檔案,避免常見的找不到檔案、編碼錯誤等問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved