[英]Java executing commands in Operating System
我有一个Java程序,可以在OS中执行特定的命令。 我还使用Process.waitfor(),如下面的代码所示,以指示执行成功完成还是失败。
我的问题是,还有其他方法可以避免使用process.waitfor(),是否可以使用while循环并执行某些操作直到该过程完成?
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdFull);
BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) == null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
try {
rc = p.waitFor();
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
我想做的是这样的
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdFull);
BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) == null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
try {
while ((rc = p.waitFor()) == true ) { // This is made up, I don't even think it would work
System.out.println('Process is going on...');
}
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
谢谢,
您可以在开始该过程之前产生一个新线程。
新线程将负责打印“正在处理...”或任何所需的内容。
在p.waitFor()完成之后,启动进程的主线程将向新线程指示它应停止运行。
您可以生成一个新线程并在线程中进行等待,并通过共享变量从主线程定期检查等待线程是否已完成。
也许这样的事情会起作用。 按照@tschaible的建议创建一个线程,然后对该线程进行超时连接(这是您在代码中组成的部分)。 它看起来像这样:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff your code here
}
});
t.run();
while (t.isAlive()) {
t.join(1000); // wait for one second
System.out.println("still waiting");
}
这样做是将代码作为单独的线程启动,然后测试胎面是否每秒完成一次。 while循环应在线程完成时结束,并且不再活动。 您可能必须检查InterruptedException,但现在无法测试。
希望这能给您正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.