在 Java 内启动外部应用程序

Starting external application inside Java

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

Read that article, good info. Also read another good example on here. It's running in a new thread now, but my program is waiting for the external application to finish before it continues, I understand that's usually desired, but not in this case, how can i disable that?

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

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