java - 尝试使用 fileProvider 从 Assets 文件夹中打开 PDF 文件,但出现 FileNotFoundException : No such file or directory

标签 java android pdf uri android-fileprovider

我正在尝试显示存储在我的 Android 应用程序的 asset 文件夹中的“NEFT.pdf”文件。
以下代码在 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,但这给了我另一个错误

android.os.fileuriexposedException 通过intent.getdata() 暴露在应用程序之外
所以我应用了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 对我来说看起来是正确的。任何人都可以帮我找到这里的错误。

这是 list 文件中的provider元素。

<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 代码

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

最佳答案

因为您想在单独的应用程序(例如 Adob​​e Reader)中显示 PDF 文件,所以我更愿意执行以下操作:-

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

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

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" />

关于java - 尝试使用 fileProvider 从 Assets 文件夹中打开 PDF 文件,但出现 FileNotFoundException : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647784/

相关文章:

android - 如何将 TextView 添加到 AppCompat PreferenceActivity

android - 在 Android 的应用程序中播放 YouTube 视频

iphone - 在 iPhone 上从 pdf 获取文本坐标

javascript - jsPDF addHTML 将低质量图像导出为 PDF

java - 如何将图片作为多部分 POST 请求的一部分发送 - Java HtmlUnit

java - Java/Swing 中的高级 RTFEditorKit

android - 在代理后面添加 Cordova/Phonegap 插件

javascript - 您能否检测到何时从浏览器 PDF 查看器打印或下载 PDF?

java - 如何衡量效率(特别是 : assembly code) for java programs?

java - Z 排序和叠加(JLabel 和 JEditorPane)