【问题标题】:java.io.FileNotFoundException: /storage/emulated/0/MyPDFDocument/questions.pdf (No such file or directory)java.io.FileNotFoundException:/storage/emulated/0/MyPDFDocument/questions.pdf(没有这样的文件或目录)
【发布时间】:2018-04-05 12:18:14
【问题描述】:

所以,我想要实现的是将回收站视图内容保存在 pdf 文件中。我已经使用 PDFDocument 类 来实现这一点。我已经添加了权限。

使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE"

我不知道我在这里做错了什么。我曾尝试更改存储的位置,但每次都出现相同的错误。

如果有人能告诉我我在这里做错了什么。下面是相关代码:

  if (selectedId == R.id.action_save_pdf) {
        // create a new document
        PdfDocument document = new PdfDocument();

        // crate a page description
        PdfDocument.PageInfo pageInfo =
                new PdfDocument.PageInfo.Builder(100, 100, 1).create();

        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);

        // finish the page
        document.finishPage(page);

        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File root = Environment.getExternalStorageDirectory();
            File dir = new File(root.getAbsolutePath() + "/MyPDFDocument");
            if (!dir.exists()) {
                dir.mkdir();
            }
            File filePath = new File(dir, "questions.pdf");

            try {
                document.writeTo(new FileOutputStream(filePath));
                Toast.makeText(this, "Saved to PDF", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "Save Unsuccessful!",
                        Toast.LENGTH_LONG).show();
            }

        } else {
            Toast.makeText(this, "External Storage not available!", Toast.LENGTH_SHORT).show();
        }

        // close the document
        document.close();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

提前谢谢你。

【问题讨论】:

  • 我认为这行File filePath = new File(dir, "questions.pdf"); 创建了必要的文件。
  • @sunilsunny 我试着按照你说的去做。还是一样的错误
  • if (!dir.exists()) { dir.mkdir(); } 那应该是:if (!dir.exists()) { if ( !dir.mkdir()) {Toast(... could not make dir ....); return;}; }。我床的目录没有创建。
  • @sunil Sunny There should be something like filePath.createNewFile(); then only that file will be created. – sunil sunny 56 mins ago。废话。 new FileOutputStream(filePath) 将创建文件。好吧,如果目录存在并授予权限。
  • thought this line File filePath = new File(dir, "questions.pdf"); creates the necessary file. 不,不会。但也不需要。

标签: java android


【解决方案1】:

我找到了自己的答案。实际上在android api level > 23中,你必须为WRITE_EXTERNAL_STORAGE请求运行时权限。由于它包含在危险权限中,因此您必须提供运行时权限以允许用户显式允许这些权限。因此,仅在清单中添加写入外部存储权限是行不通的。

以下是我用来解决问题的链接。

https://developer.android.com/training/permissions/requesting.html#java

Storage permission error in Marshmallow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多