打开失败:ENOENT(没有这样的文件或目录)即使有权限

Bre*_*uro 5 android fileoutputstream

我知道还有很多其他帖子涉及这个问题,但似乎没有一个能解决我的问题。我正在尝试在 上创建一个文件Enviroment.DIRECTORY_DOWNLOADS,通过电子邮件发送该文件,然后将其删除。但是,当我初始化文件输出流时出现错误fos = new FileOutputStream(file);

我得到的错误是:

java.io.FileNotFoundException: /CheckListReport_2015_07_19.txt: open failed: ENOENT (No such file or directory)

在我的清单中,我<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>在应用程序标签之外

下面是代码:

    String report = new SimpleDateFormat("yyyy_MM_dd").format(Calendar.getInstance().getTime());
    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);

    File file = new File(path, "CheckListReport_" + report + ".txt");

    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(file);

        String lineToWrite;
        for (Map.Entry entry : CheckboxHandler.data.entrySet()) {
            lineToWrite = entry.getKey() + ", " + entry.getValue() + "\n";
            fos.write(lineToWrite.getBytes());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    String subject = "CheckListReport_" + report + ".txt";

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"checklistreportdata@gmail.com"});
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(new File(path, "CheckListReport_" + report + ".txt").toString()));
    startActivity(Intent.createChooser(emailIntent, "Send mail..."));

    file.delete();
Run Code Online (Sandbox Code Playgroud)

Ana*_*ngh 2

使用此权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

尝试使用此代码从目录中读取文件Download

File path = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS);

File file = new File(path, "CheckListReport_" + report + ".txt");
Run Code Online (Sandbox Code Playgroud)

改变这个:

emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + Environment.DIRECTORY_DOWNLOADS + "/CheckListReport_" + report + ".txt"));
Run Code Online (Sandbox Code Playgroud)

到:

emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(new File(path, "CheckListReport_" + report + ".txt").toString()));
Run Code Online (Sandbox Code Playgroud)