Java 完成后需要处理 return

Java need process to return when finished

我的问题需要 2 个问题,但我会尽量简短。所以我需要启动一个 bat 文件。现在我是这样做的:

public static void check() throws InterruptedException{
    try {
        Runtime.getRuntime().exec("cmd /c start build.bat");
        Thread.sleep(3000);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

bat 文件启动 java 编译器编译另一个 java 文件并将错误消息导入 txt 文件。这是 bat 文件的样子:

@echo off
javac -Xstdout error.txt MainApp.java
exit

现在的问题是,我必须包括 3 秒的睡眠,以确保 error.txt 已创建并充满错误。这是非常不令人满意的。我要么需要 bat 文件中的 return 值,所以程序的其余部分等待,直到它完成 一种启动 java 的方法程序编译出来的and直接把错误信息放到一个txt文件中。

谢谢大家

您可以使用 Process#waitFor:

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated

Process p = Runtime.getRuntime().exec("cmd /c start build.bat"); 
p.waitFor();