尝试使用fileProvider从资产文件夹中打开PDF文件,但它给出FileNotFoundException:没有这样的文件或目录 [英] Trying to open PDF file from assets folder using fileProvider but it gives FileNotFoundException: No such file or directory

查看:171
本文介绍了尝试使用fileProvider从资产文件夹中打开PDF文件,但它给出FileNotFoundException:没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示存储在我的Android应用程序资产文件夹中的"NEFT.pdf"文件.
以下代码在API 25之前绝对可以正常工作

I am trying to display "NEFT.pdf" file stored in the asset folder of my android app.
The following code works absolutely fine till API 25

private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), filename);

    try {
        in = assetManager.open(filename);
        out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;


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

        startActivity(intent);
    } catch (Exception e)
    {
        Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}

此代码不适用于API 25及更高版本.它给出错误 MODE_WORLD_READABLE 不再受支持的错误.
我将其更改为 MODE_PRIVATE ,但这又给了我另一个错误

This code does not work on API 25 and above. It gives the error MODE_WORLD_READABLE no longer supported.
I changed it to MODE_PRIVATE but that gives me another error

通过intent.getdata()在应用程序之外公开的android.os.fileuriexposedException.
因此,我采用了 Developer.Android中解释的概念. com .
这是我在错误日志中得到的内容:
E/DisplayData:openFd:java.io.FileNotFoundException:没有此类文件或目录

E/PdfLoader:无法加载文件(无法打开)显示数据[PDF:NEFT.pdf] + ContentOpenable,uri:content://com.user.plansmart.provider/pdf_files/NEFT .pdf

uri对我来说似乎正确.任何人都可以帮助我在这里找到错误.

这是清单文件中的 provider 元素.

android.os.fileuriexposedexception exposed beyond app through intent.getdata().
So I applied the concept explained at Developer.Android.com.
This is what I get in the error log:

E/DisplayData: openFd: java.io.FileNotFoundException: No such file or directory

E/PdfLoader: Can't load file (doesn't open) Display Data [PDF : NEFT.pdf] +ContentOpenable, uri: content://com.user.plansmart.provider/pdf_files/NEFT.pdf

uri looks correct to me. Can Anyone help me in locating the error here.

Here is the provider element in the manifest file.

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

这是 provider_paths.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<files-path name="pdf_files" path="pdf/"/>

这是显示pdf文件的Android代码

This is the Android code to display the pdf file

private void displayFile(String filename) {
    try {
        File filePath = new File(getApplicationContext().getFilesDir(), "pdf");
        File newFile =  new File(filePath, filename);

        //new version
        Uri fileUri = FileProvider.getUriForFile(PdfFilesList.this,
                BuildConfig.APPLICATION_ID + ".provider", newFile);

        getApplicationContext().grantUriPermission(PACKAGE_NAME,
                            fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(fileUri, "application/pdf");
        intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(intent);
    }catch (Exception e){
        e.printStackTrace();
        Toast.makeText(PdfFilesList.this, "df "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}

推荐答案

因为您想在单独的应用程序(例如Adobe Reader)中显示PDF文件,所以我希望执行以下操作:-

Cause you wanna display the PDF file in a separate application (such as Adobe Reader), I would prefer doing the following:-

private void CopyReadAssets()
        {
            AssetManager assetManager = getActivity().getAssets();

            InputStream in = null;
            OutputStream out = null;
            String state = Environment.getExternalStorageState();
            if (!Environment.MEDIA_MOUNTED.equals(state)) {
                Toast.makeText(getActivity(), "External Storage is not Available", Toast.LENGTH_SHORT).show();
            }
            File pdfDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDFs");
            if (!pdfDir.exists()) {
                pdfDir.mkdir();
            }
            File file = new File(pdfDir + "/abc.pdf");

            try
            {
                in = assetManager.open("abc.pdf");
                out = new BufferedOutputStream(new FileOutputStream(file));
                copyFile(in, out);
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (Exception e)
            {
                Log.e("tag", e.getMessage());
            }
            if (file.exists()) //Checking for the file is exist or not
            {
                Uri path = Uri.fromFile(file);
                Intent objIntent = new Intent(Intent.ACTION_VIEW);
                objIntent.setDataAndType(path, "application/pdf");
                objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                Intent intent1 = Intent.createChooser(objIntent, "Open PDF with..");
                try {
                    startActivity(intent1);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(getActivity(), "Activity Not Found Exception ", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show();
            }
        }

要将文件复制到设备内存中:-

For copy file into device memory:-

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);
        }
    }

使用下面的权限

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

这篇关于尝试使用fileProvider从资产文件夹中打开PDF文件,但它给出FileNotFoundException:没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆