0

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.

cativerio
  • 3
  • 2

1 Answers1

0

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();
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • I've tried that, but the program doesn't halt here. After the bat has created the txt file it is being read. I know that the program doesn't halt because I'm getting a FileNotFoundException, error.txt not found. – cativerio Feb 08 '15 at 11:22
  • @user4542607 Try to add `/wait` after `/c`, also you don't need `start`, remove it. – Maroun Feb 08 '15 at 12:38
  • `/wait` unfortunatly does nothing. Removing `/start` however, prevents the bat file, from launching. – cativerio Feb 09 '15 at 07:12
  • I must correct myself : removing `start` wasn't bad, but adding `/wait` makes the program crash, because the bat file seems to be waiting, but the java program doesn't. However, now `waitFor()` seems to be working. This is all very strange. – cativerio Feb 09 '15 at 16:04