首页  >  文章  >  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