简体   繁体   English

等待DOS命令执行完成-Java

[英]Wait until DOS command execution has finished - Java

I am trying to import a large amount of .dmp files in a MySQL DB and since there are more than 250 files that have to be imported I wrote an app to automate the execution of the 250+ DOS commands. 我试图在MySQL数据库中导入大量.dmp文件,由于必须导入250多个文件,因此我编写了一个应用程序来自动执行250+ DOS命令。 The code for it: 它的代码:

String baseCommand = "cmd /c MySQL -h localhost -u root amateurstable < ";
Process p = Runtime.getRuntime().exec(baseCommand + filePath);

It does execute the commands it is supposed to. 它确实执行了应该执行的命令。 The problem is that some of the .dmp files are larger than 100MB, but the code above does not wait until the execution of the command is finished. 问题是某些.dmp文件大于100MB,但是上面的代码不会等到命令执行完成。

When it executes the import command for a large file it does not wait until the import is over and executes the next command right after. 当它对大文件执行导入命令时,它不会等到导入结束并立即执行下一个命令。 This causes a lot of headaches in terms of responsiveness of the computer. 就计算机的响应性而言,这引起很多麻烦。

The question is how to make it wait until the execution of the command completes? 问题是如何使其等待命令执行完成?

Runtime.exec returns a Process object that has a waitFor() method. Runtime.exec返回一个具有waitFor()方法的Process对象。

waitFor() causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. waitFor()使当前线程在必要时等待,直到此Process对象表示的进程终止。

Since you already have that Process object you could just add the call to waitFor() 由于您已经具有该Process对象,因此您只需将调用添加到waitFor()

Process p = Runtime.getRuntime().exec(baseCommand + filePath);
p.waitFor();

You could use ProcessBuilder : 您可以使用ProcessBuilder

ProcessBuilder pb = new ProcessBuilder(baseCommand + filePath, "");
Process start = pb.start();
start.waitFor();

Have you looked at Apache Commons Exec as well? 您是否也看过Apache Commons Exec?

http://commons.apache.org/exec/tutorial.html http://commons.apache.org/exec/tutorial.html

Seems like you have your processing well in hand, but I think it's a little easier to work with as a wrapper over the Runtime exec. 似乎您的处理工作已经到手,但我认为将其作为运行时执行程序的包装器要容易一些。 If you needed to kill a process it can make life easier. 如果您需要终止某个进程,则可以简化生活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM