【问题标题】:Get and parse output stream from Apache exec commons从 Apache exec commons 获取并解析输出流
【发布时间】:2014-03-28 17:35:28
【问题描述】:

我要做的是使用 avconv 捕获 IP Cam 的流。我已经设法获取该流并将其保存到使用 Java 的 apache exec commons 库的文件中,如下所示:

DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
String str = avconv_command; 
CommandLine commandLine = CommandLine.parse(str);
ExecuteWatchdog watchdog = new ExecuteWatchdog(1000000);
Executor executor = new DefaultExecutor();
executor.setWatchdog(watchdog);
executor.execute(commandLine, resultHandler);

这样,avconv 开始捕获流式传输并将其保存到文件中,在控制台上我可以看到 avconv 的工作方式和进程的输出。该输出的每一行都显示了当前正在捕获的视频的持续时间、比特率等。我需要捕获该输出并在它运行时对其进行处理。有什么想法吗?

我看过很多帖子:

Process output from apache-commons exec

How can I capture the output of a command as a String with Commons Exec?

但是他们都在进程完成后读取输出,而我需要在它运行时读取它。

【问题讨论】:

  • 想通了.. 下面回答

标签: java apache apache-commons apache-commons-exec


【解决方案1】:

通过以下方式解决了这个问题:

ByteArrayOutputStream os = new ByteArrayOutputStream();
PumpStreamHandler ps = new PumpStreamHandler(os);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
String str = avconv_command; 
CommandLine commandLine = CommandLine.parse(str);
ExecuteWatchdog watchdog = new ExecuteWatchdog(1000000);
Executor executor = new DefaultExecutor();
executor.setWatchdog(watchdog);
executor.setStreamHandler(ps);
executor.execute(commandLine, resultHandler);
Reader reader = new InputStreamReader(new ByteArrayInputStream(os.toByteArray()));
BufferedReader r = new BufferedReader(reader);
String tmp = null;
while ((tmp = r.readLine()) != null) 
{
     //Do something with tmp line
}

所以,我将输出更改为 ByteArrayOutputStream,然后读取该输出。此块必须在循环内,以便字节数组可以更新从进程输出生成的内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多