首页 > 解决方案 > 用java保存文件fiformat pdf文件

问题描述

我正在尝试创建一个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();

        }

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

标签: javapdfsavefilechooser

解决方案


close()您的代码不会FileOutputStream导致资源泄漏,并且文档无法正确访问,甚至可能已损坏。

当您使用FileOutputStreamthatimplements AutoClosable时,您有两个选择:

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();
    }
}

或者使用 a trywith resources read about that in this post例如。


推荐阅读