Running a command with Java and waiting for a command to complete

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

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 I would like the team

 refreshActionPerformed(evt); 

it is launched only after the completion of the completed package executable file. But right now it starts right after opening the command line.

How to fix it?

+6
source share
3 answers

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

 Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat"); int exitVal = p.waitFor(); 
+12
source

calling "cmd / c start" causes cmd to start another instance and exit immediately. Try to take the "start" command.

+2
source

Correct answer. I added that the window opened by the code must be closed manually.

 Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat"); int exitVal = p.waitFor(); 
0
source

Source: https://habr.com/ru/post/891144/


All Articles