生成Pdf并保存在Android中的特定文件夹中

生成Pdf并保存在Android中的特定文件夹中,android,file,pdf,Android,File,Pdf,我正在尝试生成PDF并将其保存到特定文件夹,并在成功生成PDF后打开它。但我遇到一些异常 java.io.FileNotFoundException: /storage/sdcard/PDF/demo.pdf: open failed: ENOENT (No such file or directory) 我也试过这个,但没有成功 我尝试的代码如下所示: private void cretaePDF() { Document doc = new Document();

我正在尝试生成PDF并将其保存到特定文件夹,并在成功生成PDF后打开它。但我遇到一些异常

java.io.FileNotFoundException: /storage/sdcard/PDF/demo.pdf: open failed: ENOENT (No such file or directory)
我也试过这个,但没有成功

我尝试的代码如下所示:

 private void cretaePDF() {

        Document doc = new Document();
        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            Log.d("PDFCreater", "PDF Path" + path);

            File file = new File(dir, "demo.pdf");
            FileOutputStream fout = new FileOutputStream(file);
            PdfWriter.getInstance(doc, fout);
            doc.open();
            Paragraph p1 = new Paragraph("Hi, Its me");
            doc.add(p1);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
打开PDF文件的步骤如下:

 private void openPDF() {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
        File file = new File(path, "demo.pdf");
        intent.setDataAndType(Uri.fromFile(file), "application.pdf");
        startActivity(intent);

    }

错误在哪里?

dir.mkdirs()。检查返回值。如果失败,请不要继续,而是向用户显示祝酒词并返回。您何时收到该异常?您如何知道生成了文件?FileOutputStream fout=新FileOutputStream(文件)的可能重复项;这一行向我抛出了错误。我认为该文件没有获得createdRefer以下内容:-