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

Mar*_*oun 29 java runtime.exec

我有这个代码:

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();
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*ter 47

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

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

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

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

Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat");
Run Code Online (Sandbox Code Playgroud)

根据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.");
   }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你的解释,这是有效的. (2认同)

Mik*_*ail 5

尝试/waitstart命令前添加参数.


小智 5

注释中描述的代码作为答案都不是解决方案。

第一个答案

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

第二个答案

Process p = Runtime.getRuntime().exec("cmd /c " + path + "\\RunFromCode.bat");
Run Code Online (Sandbox Code Playgroud)

第三个答案

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.");
   }
}
Run Code Online (Sandbox Code Playgroud)