【问题标题】:how to get the output of a background running script in servlet如何在servlet中获取后台运行脚本的输出
【发布时间】:2018-01-10 07:47:16
【问题描述】:

我正在使用 Runtime.getRuntime().exec() 通过 java 调用脚本,并让脚本在后台运行以创建文件,如何在文件完成时在 servlet 中获取输出,即使在其他页面上工作

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    这是获取命令执行输出的代码,但是您无法获取需要更多时间的后台进程的输出。对于更耗时的命令,您必须使用 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);
        }
    }
    

    【讨论】:

    • 感谢您的回复。但是我想在文件创建任务完成时使用 ftp 下载文件,因为我想读取在后台运行的脚本的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多