我正在从我的程序运行一个.exe
文件,并且需要一定的时间。此命令的输出在以下语句中用于进一步处理。输出是一个布尔变量。但是程序会立即返回false
,但实际上该命令仍在执行中并且需要一定的时间。由于 false 值,后续语句将引发错误。我该如何处理这种情况。return_var = exec(pagecmd)
是执行语句。
boolean return_var = false;
if("true".equals(getConfig("splitmode", ""))){
System.out.println("Inside splitmode if**********************");
String pagecmd = command.replace("%", page);
pagecmd = pagecmd + " -p " + page;
File f = new File(swfFilePath);
System.out.println("The swffile inside splitmode block exists is -----"+f.exists());
System.out.println("The pagecmd is -----"+pagecmd);
if(!f.exists()){
return_var = exec(pagecmd);
System.out.println("The return_var inside splitmode is----"+return_var);
if(return_var) {
strResult=doc;
}else{
strResult = "Error converting document, make sure the conversion tool is installed and that correct user permissions are applied to the SWF Path directory" +
getDocUrl();
}
结合 Andreas 建议的 waitFor(),您可能还需要使用 exec() 返回的进程对象的 getInputStream 来检索您正在执行的程序写入的数据。
假设您最终在 exec()
方法中使用了 Runtime.exec()
,您可以使用从 Runtime.exec()
返回的 Process
对象的 waitFor()
方法来等待执行完成:
...
Process p = Runtime.getRuntime().exec(pagecmd);
int result = p.waitFor();
...
来自 waitFor()
的返回值是子进程的退出代码。
如果实际需要从子进程写入其stderr
或stdout
通道的子进程读取输出,则需要使用 Process.getInputStream()
(注意:不是getOutputStream()
)并Process.getErrorStream()
并读取这些流的子进程输出。然后,检查流的 read()
方法的返回值,以检查子进程是否已终止(或至少关闭其输出流)而不是使用 waitFor()
。
此外,对于这类问题,您应该考虑使用 Apache commons exec 库。
或者,您可能需要检查ProcessBuilder
类。