Search code examples
javabatch-filejavacompiler

Java need process to return when finished


my problem would take 2 questions, but I'll keep it short. So I need to launch a bat file. Right now I do it like this:

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

The bat file launches the java compiler to compile another java file and direct the error messages into a txt file. This is what the bat file looks like:

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

Now the problem is, that I have to include a 3 second sleep, in order to be sure, that the error.txt has been created and filled with errors. This is very unsatisfying. I'd either need a return value from the bat file, so I the rest of the program waits, until it's done or a way to launch the java compiler out of the program and direct the error messages into a txt file.

Thanks everybody.


Solution

  • You can use 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();