保存文件,然后使用javafx打开它

时间:2015-07-27 10:47:13

标签: javafx

我的项目目录中存有一个文件。我对它进行了一些更改,然后使用FileChooser保存的对话框保存它。保存后我希望在我的系统中自动打开此文件。 我成功保存了文件但没有得到如何在没有用户从打开的对话框中选择它的情况下自动打开它。 保存文件的代码如下所示。

String input = "";
            try {
                OutputStream outStream = null;
                ipFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("upgradeworkbench/Resources/IP_template.sh");
                Stage stage = new Stage();
                stage.setTitle("Save");
                byte[] buffer = null;

                buffer = new byte[ipFile.available()];
                ipFile.read(buffer);
                FileChooser fileChooser = new FileChooser();
                fileChooser.setInitialFileName("IP_template");
                fileChooser.getExtensionFilters().addAll(
                        new FileChooser.ExtensionFilter("Development File", "*.sh")
                );
                fileChooser.setTitle("Save File");
                File file = fileChooser.showSaveDialog(stage);
                if (file != null) {
                    outStream = new FileOutputStream(file);
                    outStream.write(buffer);
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    while ((line = reader.readLine()) != null) {
                        input += line + System.lineSeparator();
                    }
                    input = input.replace("LogPath=$logPath", "LogPath=");
                    input = input.replace("ProcFileName=$ProcFileName", "ProcFileName=");
                    input = input.replace("BinFileName=$BinFileName", "BinFileName=");
                    input = input.replace("ReportFileName=$RepFileName", "ReportFileName=");
                    input = input.replace("FormFileName=$FormFileName", "FormFileName=");
                    input = input.replace("custom entries to be made by java code here", "file created");
                    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                    writer.write(input);
                    writer.flush();
                    writer.close();
                    reader.close();
                }
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }

请帮助我如何在保存到本地驱动器中后立即打开此文件。

P.S:我不想使用fileChooser.showOpenDialog(stage)打开一个对话框并选择打开该文件。我想让它自动打开。

2 个答案:

答案 0 :(得分:2)

您可以使用Java Desktop API

Desktop.getDesktop().open(new File(yourfilename));

答案 1 :(得分:1)

对于JavaFX解决方案,请使用HostServices

// getHostServices() is an Application method. You may
// need to call this in your Application subclass and expose
// it to the rest of the application somehow, depending on your
// application structure:
HostServices hostServices = getHostServices() ; 
hostServices.showDocument(file.toURI().toString());