Runtime.exec()。waitFor()不会等到进程完成

我有这个代码:

File file = new File(path + "\\RunFromCode.bat"); file.createNewFile(); PrintWriter writer = new PrintWriter(file, "UTF-8"); for (int i = 0; i <= MAX; i++) { writer.println("@cd " + i); writer.println(NATIVE SYSTEM COMMANDS); // more things } writer.close(); Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat"); p.waitFor(); file.delete(); 

发生的事情是文件在实际执行之前被删除。

这是因为.bat文件只包含本机系统调用吗? 如何在执行.bat文件进行删除? (我不知道.bat文件的输出是什么,因为它会动态更改)。

通过使用start ,您要求cmd.exe在后台启动批处理文件:

 Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat"); 

因此,从后台进程完成之前,从Java( cmd.exe )启动的进程将返回。

删除start命令以在前台运行批处理文件 – 然后, waitFor()将等待批处理文件完成:

 Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat"); 

根据OP,让控制台窗口可用是很重要的 – 这可以通过添加/wait参数来完成,如@Noofiz所建议的那样。 以下SSCCE为我工作:

 public class Command { public static void main(String[] args) throws java.io.IOException, InterruptedException { String path = "C:\\Users\\andreas"; Process p = Runtime.getRuntime().exec("cmd /c start /wait " + path + "\\RunFromCode.bat"); System.out.println("Waiting for batch file ..."); p.waitFor(); System.out.println("Batch file done."); } } 

如果RunFromCode.bat执行EXIT命令,则命令窗口将自动关闭。 否则,命令窗口将保持打开状态,直到您使用EXIT显式退出它 – 在任何一种情况下,java进程都会等待窗口关闭。

尝试在start命令前添加/wait参数。

 waitForProcessOutput() 

为我们做了诀窍。

看到:

http://docs.groovy-lang.org/docs/groovy-1.7.2/html/groovy-jdk/java/lang/Process.html#waitForProcessOutput()

代码示例(在SOAPUI中使用)

 def process = "java -jar ext\\selenese-runner.jar".execute() process.waitForProcessOutput() def exitValue = process.exitValue() 

评论中描述的代码中没有一个代表答案是解决方案。

第一个答案

 Process p = Runtime.getRuntime().exec("cmd /c start " + path + "\\RunFromCode.bat"); 

第二个答案

 Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat"); 

第三个答案

 public class Command { public static void main(String[] args) throws java.io.IOException, InterruptedException { String path = "C:\\Users\\andreas"; Process p = Runtime.getRuntime().exec("cmd /c start /wait " + path + "\\RunFromCode.bat"); System.out.println("Waiting for batch file ..."); p.waitFor(); System.out.println("Batch file done."); } }