Runtime.exec()无法正常完成

时间:2012-02-21 21:17:55

标签: java servlets runtime exec

我创建了一个依赖外部脚本来收集用户查询请求的WebApp(内部软件)。我已经测试了netbeans提供的webfish服务器上的WebApp,但每当我尝试将我的应用程序上传到第三方服务器(Apache Tomcat)时,我遇到了process.getRuntime exitValue的问题,从未编写过WebApp永远不会进入结果页面....

这是我到目前为止实施的代码:

更新 - >在读取stderr和stdin后,代码现在可以工作了:

        pd = new ProcessBuilder("runscript.bat");
        pd.redirectErrorStream(true);
        process = pd.start();


        StreamGobbler inputGobbler = new StreamGobbler(process.getInputStream(), "Input");
        StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(),"Error");

        errorGobbler.start();
        inputGobbler.start();

        int exitVal = -1;

        try {
            exitVal = process.waitFor();
        } catch (InterruptedException ex) {
            //log Error
        }

class StreamGobbler extends Thread {
     OutputWriterReader outWR = new OutputWriterReader();
     BufferedWriter deadWriter;
     InputStream is;

// reads everything from is until empty. 
StreamGobbler(InputStream is, String type) {
    this.is = is;
    createWatch(type);
}
// depending on if Error stream or Input Stream
private void createWatch(String type){
    try {

        if(type.equals("Error"))
            deadWriter = new BufferedWriter(new FileWriter("StdError.txt"));
        else if(type.equals("Input"))
            deadWriter = new BufferedWriter(new FileWriter("StdInput.txt"));

    } catch (IOException ex) {
        //log Error
    }
}

@Override
public void run() {
    try {            
        InputStreamReader isr = new InputStreamReader(this.is);
        BufferedReader br = new BufferedReader(isr);
        String line=null;

        while ( (line = br.readLine()) != null)
            deadWriter.append(line);

        deadWriter.flush();
        deadWriter.close();

    } catch (IOException ioe) {
        //log Error
    }
}

}

任何建议?在此先感谢您的任何帮助

1 个答案:

答案 0 :(得分:3)

当您在其上调用exitValue()时,该过程可能无法完成。

在process.exitValue()调用之前添加: process.waitFor();