在Java中启动外部应用程序

时间:2017-07-12 21:41:13

标签: java javafx processbuilder

我无法从JavaFX GUI启动应用程序。我正在使用ProcessBuilder。它创建了这个过程,但是在我关闭Java程序之前,应用程序不会启动。是因为特定程序正在等待我的代码的参数或错误吗?

@FXML
private void runWorldpac() {
    try {
        ProcessBuilder process = new ProcessBuilder("C:\\speedDIAL\\speedDIAL.exe");
        Process p = process.start();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

外部应用程序启动但不允许与原始应用程序进行任何交互,直到我关闭此外部程序。尝试运行一个新线程,结果相同。 这是新代码:

try {
            ProcessBuilder process = new ProcessBuilder("C:\\speedDIAL\\speedDIAL.exe");
            Map<String, String> environ = process.environment();
            Process p = process.start();
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
            }
            System.out.println("Program terminated!");
        } catch (IOException e) {
            e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:2)

  

阅读那篇文章,好消息。另请阅读此处的另一个好例子。它现在正在一个新线程中运行,但我的程序正在等待外部应用程序在继续之前完成,我明白这通常是需要的,但在这种情况下,我怎么能禁用它?

等待在新线程中生成退出值。类似的东西:

try {
    ProcessBuilder pBuilder = new ProcessBuilder("C:\\speedDIAL\\speedDIAL.exe");

    // don't forget to handle the error stream, and so 
    // either combine error stream with input stream, as shown here
    // or gobble it separately
    pBuilder.redirectErrorStream(true); 
    final Process process = pBuilder.start();
    final InputStream is = process.getInputStream();

    // in case you need to send information back to the process
    // get its output stream. Don't forget to close when through with it
    final OutputStream os = process.getOutputStream();

    // thread to handle or gobble text sent from input stream 
    new Thread(() -> {
        // try with resources
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is));) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                // TODO: handle line
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }).start();

    // thread to get exit value from process without blocking 
    Thread waitForThread = new Thread(() -> {
        try {
            int exitValue = process.waitFor();
            // TODO: handle exit value here
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    waitForThread.start();

    // if you want to join after a certain time:
    long timeOut = 4000;
    waitForThread.join(timeOut);
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}