Runtime.exec()。waitFor()不会等到进程完成 [英] Runtime.exec().waitFor() doesn't wait until process is done

查看:1582
本文介绍了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();

在实际执行文件之前删除的文件会发生什么。

What happens is that the file deleted before it actually executed.

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

Is this because the .bat file contains only native system call? How can I make the deletion after the execution of the .bat file? (I don't know what the output of the .bat file will be, since it dynamically changes).

推荐答案

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

By using start, you are askingcmd.exe to start the batch file in the background:

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

那么,从Java启动的进程( cmd.exe )在后台进程完成之前返回。

So, the process which you launch from Java (cmd.exe) returns before the background process is finished.

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

Remove the start command to run the batch file in the foreground - then, waitFor() will wait for the batch file completion:

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






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


According to OP, it is important to have the console window available - this can be done by adding the /wait parameter, as suggested by @Noofiz. The following SSCCE worked for me:

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进程都会等待窗口关闭。

If RunFromCode.bat executes the EXIT command, the command window is automatically closed. Otherwise, the command window remains open until you explicitly exit it with EXIT - the java process is waiting until the window is closed in either case.

这篇关于Runtime.exec()。waitFor()不会等到进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆