【问题标题】:How can I capture the output of a command as a String with Commons Exec?如何使用 Commons Exec 将命令的输出捕获为字符串?
【发布时间】:2017-04-05 19:14:25
【问题描述】:

Commons exec 提供了一个 PumpStreamHandler,它将标准输出重定向到 Java 进程的标准输出。如何将命令的输出捕获到字符串中?

【问题讨论】:

    标签: java


    【解决方案1】:

    他就是我发现的:

    import java.io.ByteArrayOutputStream;
    import org.apache.commons.exec.CommandLine;
    import org.apache.commons.exec.DefaultExecutor;
    import org.apache.commons.exec.Executor;
    import org.apache.commons.exec.PumpStreamHandler;
    
    public String execToString(String command) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CommandLine commandline = CommandLine.parse(command);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        exec.execute(commandline);
        return(outputStream.toString());
    }
    

    【讨论】:

    • 对于一个长时间运行的任务,我想在前端实时显示命令行执行日志。如何通过 OutputStream 采集实时日志?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多