从Apache exec commons获取并解析输出流

时间:2014-03-28 17:35:29

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

我要做的是使用avconv捕获IP Cam的流。我已经设法获取该流并使用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?

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

1 个答案:

答案 0 :(得分: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,然后读取该输出。此块必须位于循环内,因此字节数组可以更新从进程输出生成的内容