首頁  >  文章  >  Java  >  如何從 Android 應用程式中的 Assets 資料夾讀取 PDF 檔案?

如何從 Android 應用程式中的 Assets 資料夾讀取 PDF 檔案?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-29 01:52:30248瀏覽

How to Read a PDF File from the Assets Folder in an Android App?

從資源資料夾讀取PDF 檔案

本文解決了在Android 應用程式中從資源資料夾讀取PDF 文件的問題。嘗試存取 PDF 的使用者遇到錯誤訊息「檔案路徑無效。」

程式碼分析

提供的程式碼從資產資料夾擷取 PDF 檔案。但是,在 Intent 中指定開啟 PDF 的路徑引用了 asset 資料夾,這可能會導致權限和存取問題。

解決方案

要解決此問題,請考慮以下程式碼:

public class SampleActivity extends Activity {<pre class="brush:php;toolbar:false">@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    CopyReadAssets();
}

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();
        out.flush();
        out.close();
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

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

    //Grant permission to the user after confirming existence of the file
    if (file.exists()) {
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            getApplicationContext().startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "NO PDF Viewer", Toast.LENGTH_SHORT).show();
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

}

說明

  • 此程式碼將PDF 檔案從asset 資料夾讀取到應用程式內部儲存中讀取的文件中。
  • Intent 中的路徑現已更新為指向中的檔案內部存儲,確保存取權限。
  • 此方法消除了「檔案路徑無效」錯誤。

其他注意事項

  • 確保在清單文件中授予 WRITE_EXTERNAL_STORAGE 權限。
  • 確保 PDF 檔案存在於資產資料夾中的指定位置。

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

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