【发布时间】:2018-01-10 07:47:16
【问题描述】:
我正在使用 Runtime.getRuntime().exec() 通过 java 调用脚本,并让脚本在后台运行以创建文件,如何在文件完成时在 servlet 中获取输出,即使在其他页面上工作
【问题讨论】:
我正在使用 Runtime.getRuntime().exec() 通过 java 调用脚本,并让脚本在后台运行以创建文件,如何在文件完成时在 servlet 中获取输出,即使在其他页面上工作
【问题讨论】:
这是获取命令执行输出的代码,但是您无法获取需要更多时间的后台进程的输出。对于更耗时的命令,您必须使用 javascript 来安排命令,您可以定期轮询命令输出。
public void executeAndGetResponse( HttpServletResponse response ) {
Process process = Runtime.getRuntime().exec( "some command" );
if( process != null ) {
int status = process.getWaitFor(); // wait for completion
InputStream in = null;
if( status == 0 ) {
in = process.getInputStream(); // if success get output
} else {
in = process.getErrorStream(); // if failure get error
}
OutputStream out = response.getOutputStream();
org.apache.commons.io.IOUtils.copy(in,out);
}
}
【讨论】: