首頁  >  文章  >  Java  >  如何從 Android 中的 Assets 資料夾開啟 PDF 檔案?

如何從 Android 中的 Assets 資料夾開啟 PDF 檔案?

Susan Sarandon
Susan Sarandon原創
2024-10-29 00:54:29404瀏覽

How to Open a PDF File from the Assets Folder in Android?

從資源資料夾讀取PDF 檔案

問題:
從應用程式的讀取PDF 檔案時在assets資料夾中,選擇應用程式開啟檔案後,遇到錯誤訊息「檔案路徑無效」。

解決方案:

問題在於PDF 檔案的檔案路徑。要修正此問題,請按照以下步驟操作:

1.將PDF 檔案複製到應用程式的檔案目錄

<code class="java">private void CopyReadAssets() {
    AssetManager assetManager = getAssets();

    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), "abc.pdf");
    try {
        in = assetManager.open("abc.pdf");
        out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}</code>

此程式碼將「abc. pdf」檔案從資產資料夾複製到應用程式的檔案目錄,確保您有權存取該檔案。

2。更新意圖以使用新檔案路徑

<code class="java">Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
                    Uri.parse("file://" + getFilesDir() + "/abc.pdf"),
                    "application/pdf");</code>

此程式碼更新意圖以指向應用程式檔案目錄中複製的 PDF 檔案。

3.新增寫入外部儲存的權限

<code class="xml"><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></code>

在AndroidManifest.xml檔案中加入該權限,授予應用程式存取外部儲存進行檔案操作的權限。

現在,當使用者點擊 DOCS 按鈕時,應用程式應成功讀取並顯示 PDF 檔案。

以上是如何從 Android 中的 Assets 資料夾開啟 PDF 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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