从 Java 执行命令并等待命令完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6444812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:58:38  来源:igfitidea点击:

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

javabatch-filecommandexecexecute

提问by Matt R. Johnson

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

在我的 Java 程序中,我创建了一个进程,该进程执行一个命令来运行这样的批处理文件:

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?

我该如何解决?

采纳答案by Matt R. Johnson

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

我设法在别处找到了答案。要保持初始进程打开直到批处理文件完成,您只需要“/wait”

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

回答by Triton Man

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

调用“cmd /c start”会导致 cmd 触发另一个实例并立即退出。尝试取出“开始”命令。

回答by Pedro Arnoldo Machado Duran

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