首頁  >  文章  >  Java  >  為什麼我的 Android 應用程式在嘗試從資源資料夾讀取 PDF 時會拋出「檔案路徑無效」錯誤?

為什麼我的 Android 應用程式在嘗試從資源資料夾讀取 PDF 時會拋出「檔案路徑無效」錯誤?

Patricia Arquette
Patricia Arquette原創
2024-10-28 09:48:29750瀏覽

Why is my Android app throwing a

從資源資料夾讀取PDF 檔案

問題:

問題:

程式碼:

<code class="java">File file = new File("android.resource://com.project.datastructure/assets/abc.pdf");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
startActivity(intent);</code>

相關程式碼部分如下:

解決方案:

<code class="java">AssetManager assetManager = getAssets();
InputStream in = assetManager.open("abc.pdf");
OutputStream out = openFileOutput("abc.pdf", Context.MODE_WORLD_READABLE);

// Copy PDF file to internal storage
copyFile(in, out);

// Create Intent and URI for file in internal storage
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + getFilesDir() + "/abc.pdf"), "application/pdf");

startActivity(intent);</code>

問題在於提供給File 物件的路徑。正確的路徑應該使用 getAssets() 從資源資料夾中擷取 PDF 檔案。

    附加說明:
  • 不要忘記新增清單檔案的 WRITE_EXTERNAL_STORAGE 權限。
  • copyFile() 方法用於將 PDF 文件從 asset 資料夾複製到內部存儲,使其可以被 Intent 存取。
URI 是使用 Uri.parse() 建構以指向內部儲存中檔案的位置。

以上是為什麼我的 Android 應用程式在嘗試從資源資料夾讀取 PDF 時會拋出「檔案路徑無效」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn