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

Java 讀取 resources/raw 或 assets 目錄下檔案的正確姿勢

     編輯:程式設計綜合問答

問題背景

嘗試 new File("image1") 讀取專案 res/raw 或 assets 目錄下的檔案,拋出 FileNotFoundException。這兩個目錄不對應實體檔案系統路徑,無法用 java.io.File 直接存取。

正確讀取方式

1. res/raw 目錄:使用 Resources.openRawResource()

檔案編譯進 APK,透過 R.raw.filename 取得資源 ID。

public static String readRaw(Context context, @RawRes int resId) throws IOException {
    try (InputStream is = context.getResources().openRawResource(resId);
         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();
    }
}

// 呼叫
String content = readRaw(this, R.raw.my_file);  // 檔名不含副檔名

2. assets 目錄:使用 AssetManager.open()

檔案保持原始結構,支援子目錄,需包含副檔名。

public static String readAsset(Context context, String fileName) throws IOException {
    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();
    }
}

// 呼叫
String content = readAsset(this, "folder/my_file.txt");  // 含路徑與副檔名

3. 取得二進位資料(圖片等)

public static byte[] readRawBytes(Context context, @RawRes int resId) throws IOException {
    try (InputStream is = context.getResources().openRawResource(resId);
         ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[4096];
        int len;
        while ((len = is.read(buffer)) != -1) bos.write(buffer, 0, len);
        return bos.toByteArray();
    }
}

常見誤區

  • new File("name"):只能存取內部/外部儲存體的實體檔案,不能存取 res/ 或 assets/。
  • MultipartEntity 上傳:若需上傳 raw/assets 檔案,先用上述方法讀取為 byte[],再用 ByteArrayBody 或寫入暫存檔後上傳。
  • 大檔案:assets 無大小限制,res/raw 單檔建議 < 1MB(受資源表限制)。

選擇建議

特性res/rawassets
資源 ID自動產生 R.raw.xxx無,需字串路徑
子目錄不支援支援
編譯時壓縮可能(PNG 等)不壓縮,原樣封裝
適用場景小型固定資源(JSON、XML、短音訊)大檔、結構化資料、字體、資料庫種子

理解 Android 資源封裝機制,選對讀取 API,才能避開 FileNotFoundException 坑。

  1. 上一篇文章:
  2. 下一篇文章:
Struts2 `` 與原生 `