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