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

非 Y 不嫁゛ 提交于 2019-12-18 13:19:29

问题


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?


回答1:


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();



回答2:


calling "cmd /c start" causes cmd to fire off another instance and exit immediately. Try taking out the "start" command.




回答3:


The answer given is correct. I added that the window opened by the code needs to be closed manually.

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


来源:https://stackoverflow.com/questions/6444812/executing-a-command-from-java-and-waiting-for-the-command-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!