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

时间:2015-07-19 19:02:46

标签: 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();

1 个答案:

答案 0 :(得分:2)

使用此权限:

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

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

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

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

改变这个:

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

为:

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