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

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

我想要做的是使用 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?

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

最佳答案

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

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,然后读取该输出。该 block 必须位于循环内,以便字节数组可以更新从进程输出生成的内容

关于java - 从 Apache exec commons 获取并解析输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22719659/

相关文章:

java - 授权 App Engine Java Servlet 在 eclipse 中使用 Cloud SQL

java - Talend——一行到多行,可变数量的输出行

java - 构造函数拦截器之后和之前

php - Apache 一个 URL 上的多个框架

Apache Mod_Rewrite 问号

python - 如何解决: Truncated or oversized response headers received from daemon process

java - Web 应用程序测试中的完整字段从 Python/Eclipse/DyDev 中的映射文档调用数据

java.lang.NoClassDefFoundError : org/apache/commons/codec/binary/Base64: from a library jar imported with Maven

java - 将 Collection<myClass> 转换为 Collection<String>

java - 解析内容中的封装器未正确转义的 CSV 文件