用java保存文件格式的pdf文件

用java保存文件格式的pdf文件,java,pdf,save,filechooser,Java,Pdf,Save,Filechooser,我正在尝试创建一个pdf文件,然后使用fileChooser将其保存到设备 它可以保存,但当我打开文件时,它不会打开 这是我的密码 FileChooser fc = new FileChooser(); fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd")); fc.setTitle("Save to P

我正在尝试创建一个pdf文件,然后使用fileChooser将其保存到设备 它可以保存,但当我打开文件时,它不会打开 这是我的密码

 FileChooser fc = new FileChooser();
        fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
        fc.setTitle("Save to PDF"
        );
        fc.setInitialFileName("untitled.pdf");
        Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();

        File file = fc.showSaveDialog(stg);
        if (file != null) {
            String str = file.getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(str);
            Document document = new Document();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
            document.open();
            document.add(new Paragraph("A Hello World PDF document."));
            document.close();
            writer.close();

            fos.flush();

        }

当我打开它时,这是一个错误,显示该文件已被其他用户打开或使用

您的代码未
close()
文件输出流,这可能导致资源泄漏,文档无法正确访问,甚至可能已损坏

使用实现自动关闭的
文件输出流
时,有两个选项:

close()
FileOutputStream
手动:

FileChooser fc = new FileChooser();
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
    fc.setTitle("Save to PDF");
    fc.setInitialFileName("untitled.pdf");
    Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();

    File file = fc.showSaveDialog(stg);
    if (file != null) {
        String str = file.getAbsolutePath();
        FileOutputStream fos = new FileOutputStream(str);
        Document document = new Document();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
        document.open();
        document.add(new Paragraph("A Hello World PDF document."));
        document.close();
        writer.close();

        fos.flush();
        /*
         * ONLY DIFFERENCE TO YOUR CODE IS THE FOLLOWING LINE
         */
        fos.close();
    }
}

或者使用
尝试
,例如,在中阅读相关资源。

您是否关闭了
文件输出流
?我只能看到你
flush()
it
close()
flush()
@deHaar()之后关闭它是的,谢谢你这么多,你可以把它放在一个独立的答案中,这样我就可以将它标记为答案我不知道我应该关闭文件输出流我以为我们只关闭了文档