FileProvider - 由于FileNotFoundException无法保存文件:/Download/TempFile.html(没有这样的文件或目录)

时间:2016-09-02 16:00:24

标签: java android android-fileprovider

似乎现在Android N需要FileProvider,所以我试图实现FileProvider将文件从网络保存到本地临时位置,然后我需要读取这个临时文件。

我这样做是为了设置FileProvider:

的Manifest.xml:

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

然后我的provider_paths.xml文件夹中有一个res/xml文件,其中包含:

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

最后,这是我创建临时文件的java代码:

try {

    final File imagePath = new File(getContext().getFilesDir(), "Download");
    final File newFile = new File(imagePath, filename + "." + filePrefix);

    final Uri contentUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", newFile);

    final File tempFile = new File(contentUri.getPath());

    tempFile.getParentFile().mkdirs();
    final FileWriter writer = new FileWriter(tempFile);
    writer.flush();
    writer.close();
    return tempFile;
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

final FileWriter writer = new FileWriter(tempFile);行引发异常java.io.FileNotFoundException: /Download/TempFile.html (No such file or directory)

有关我做错的任何建议吗?谢谢!

更新/编辑:

保存文件的当前方法将文件放在此处: /storage/emulated/0/Download/TempFile.html

这很好,直到我尝试使用Intent消耗它,如下所示:

final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), fileType.getMimeType());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

然后抛出此异常:

android.os.FileUriExposedException:file:///storage/emulated/0/Download/TempFile.html exposed beyond app through Intent.getData()

1 个答案:

答案 0 :(得分:1)

  

似乎现在Android N需要FileProvider

它将被普遍使用,但仅用于将内容提供给其他应用程序。您的需求似乎不包括将内容提供给其他应用程序。

  

我尝试实施FileProvider将文件从网络保存到本地临时位置

您的问题中没有与网络有关的代码。

  

关于我做错了什么的任何建议?

getPath()上拨打Uri通常是无用的。充其量,如果Uri的方案是file,则可能会有用。 FileProvider专门设计为为您提供Uri方案file,而是content方案。 Uri的路径不会直接表示设备上的文件,只有/questions/39296553/fileprovider-cant-save-file-due-to-filenotfoundexception-download-tempfile(此网页的URL路径)表示计算机上文件的路径。

除此之外,您不需要FileProvider来制作临时文件,而您确实需要FileProvider来通过网络下载内容。

更新(基于问题更新)

首先,在Uri.fromFile(file)逻辑中将FileProvider.getUriForFile(file)替换为Intent

其次,如果您确实要将文件存储在/storage/emulated/0/Download/TempFile.html中,则需要在external-path配置中使用FileProvider,而不是files-path。如果您将下载的文件存储在files-path中,则会getFilesDir()。您的/storage/emulated/0/Download/TempFile.html路径似乎不在Environment.getExternalStorageDirectory()