0

I am trying to create a pdf file then save it to device using fileChooser It works the saving but when i go to the file to open it it doesn't open here is my code

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

        }

when i open it this is the error showing it says the file is either opened or used by another user

Isra
  • 13
  • 3
  • Have you closed the `FileOutputStream`? I can only see that you `flush()` it... `close()` it after the `flush()`. – deHaar Sep 27 '20 at 10:03
  • @deHaar yes thank you so much it worked u can put it in an independant answer so as i can mark it as answered – Isra Sep 27 '20 at 10:13
  • I didn''t know i sould close FileOutputStream i thought we only close document – Isra Sep 27 '20 at 10:14

1 Answers1

0

Your code does not close() the FileOutputStream which may cause a resource leak and the document is not properly accessible, maybe even corrupted.

When you work with a FileOutputStream that implements AutoClosable, you have two options:

close() the FileOutputStream manually:

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

or use a try with resources read about that in this post, for example.

deHaar
  • 17,687
  • 10
  • 38
  • 51