如何将创建的文件保存到 Java 中用户指定的文件路径?

How to save created file to the user specified filepath in Java?

这可能是个常见问题,但我没有找到确切的解决方案。 我有一个 JavaFX 应用程序,它使用来自云 sql 服务器的数据创建 PDF 文件(使用 iText 7)。 但是,这个文件现在保存在我指定的文件路径中。 我希望我的用户指定 he/she 想要保存该文件的位置。

String dest = "itextData//singleLR.pdf";
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);

现在这里,路径dest已经指定了。我希望它由用户指定。

Expected output
//File browsing code on button click
//Got String in variable user_specified_path

String dest = user_specified_path;
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);

按照@VGR 的建议,我使用了 JavaFX FileChooser。 但是,我使用了 fileChooser.showSaveDialog(scene);

而不是 fileChooser.showOpenDialog(scene)

showOpenDialog() 用于打开现有文件。 showSaveDialog() 用于创建新文件

所以我的代码如下所示,

print.setOnAction(event -> {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Save PDF File");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PDF File", "*.pdf"));
        File selectedFile = fileChooser.showSaveDialog(print.getScene().getWindow());
        if (selectedFile != null) {
           String dest = selectedfile.getAbsolutePath();
           PdfWriter writer = new PdfWriter(dest);
           PdfDocument pdf = new PdfDocument(writer);
           Document document = new Document(pdf);
           //DOCUMENT WRITING CODE BEGINS
         }
}

供参考 -> Saving File with FileChooser in JavaFX