【问题标题】:saving a file fiormat pdf file with java用java保存文件fiformat pdf文件
【发布时间】:2020-09-27 09:59:33
【问题描述】:

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

        }

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

【问题讨论】:

  • 你关闭FileOutputStream了吗?我只能看到你flush()它...close()它在flush()之后。
  • @deHaar 是的,非常感谢它的工作,你可以把它放在一个独立的答案中,这样我就可以将它标记为已回答
  • 我不知道我应该关闭 FileOutputStream 我以为我们只关闭文档

标签: java pdf save filechooser


【解决方案1】:

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

当您使用FileOutputStreamimplements 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();
    }
}

或使用try 与在this post 中阅读的资源,例如。

【讨论】:

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