如何解决Runtime.execwaitFor不会等待过程完成
通过使用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进程一直在等待,直到在两种情况下都关闭了窗口。
解决方法
我有这个代码:
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
文件的输出是什么,因为它是动态变化的)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。