Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a Command from Java and Waiting for the Command to Finish

In my Java program, I create a process that executes a command to run a batch file like this:

try {
        File tempFile = new File("C:/Users/Public/temp.cmd");
        tempFile.createNewFile();
        tempFile.deleteOnExit();


        setContents(tempFile, recipe.getText()); //Writes some user input to file
        String cmd = "cmd /c start " + tempFile.getPath();


        Process p = Runtime.getRuntime().exec(cmd);


        int exitVal = p.waitFor();

        refreshActionPerformed(evt);

    } catch (InterruptedException ex) {
        Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) {
        Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
    } 

Now, what I would like to have happen is that the command

refreshActionPerformed(evt);

runs only after the batch file I called has finished executing. But right now, it runs immediately after the Command Prompt opens.

How do I fix this?

like image 479
Matt R. Johnson Avatar asked Jun 22 '11 18:06

Matt R. Johnson


1 Answers

I manged to find the answer elsewhere. To keep the initial process open until the batch file finished all you need is "/wait"

Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat");
int exitVal = p.waitFor();
like image 129
Matt R. Johnson Avatar answered Nov 16 '22 00:11

Matt R. Johnson