Java 循环中的Runtime.getRuntime().exec()

Java 循环中的Runtime.getRuntime().exec(),java,loops,ffmpeg,runtime,exec,Java,Loops,Ffmpeg,Runtime,Exec,我正在编写一个小工具,用java自动创建一些缩略图 因此,我执行Runtime.getRuntime().exec(命令)

我正在编写一个小工具,用java自动创建一些缩略图

因此,我执行
Runtime.getRuntime().exec(命令)
循环中进行编码。
现在我的问题是,只创建了第一个缩略图

到目前为止,我的代码是:

public static void testFFMpeg(File videoFile) throws IOException {
    FFMpegWrapper wraper = new FFMpegWrapper(videoFile);
    int length = (int) wraper.getInputDuration() / 1000;
    String absolutePath = videoFile.getAbsolutePath();
    String path = absolutePath.substring(0, absolutePath.lastIndexOf('/') + 1);
    int c = 1;
    System.out.println(path + "thumb_" + c + ".png");
    for (int i = 1; i <= length; i = i + 10) {
        int h = i / 3600;
        int m = i / 60;
        int s = i % 60;
        String command = "ffmpeg -i " + absolutePath + " -ss " + h + ":" + m + ":" + s + " -vframes 1 " + path
            + "thumb_" + c + "_" + videoFile.getName() + ".png";
        System.out.println(command);
        Runtime.getRuntime().exec(command);
        c++;
    }
}
因此,循环运行良好,命令也运行良好,如果我从命令行手动运行它,它将创建每个缩略图,因此似乎存在一个问题,即在2。调用
Runtime.getRuntime().exec(命令)未开始,因为第一次运行尚未完成


S是否有可能暂停线程或类似的操作,直到
Runtime.getRuntime().exec(command)运行命令已完成?

因为您当前在一个线程中运行它,所以每次执行命令时尝试打开一个新线程。并在完成进程后加入线程创建缩略图。

运行时。exec
返回一个
进程
实例,可用于监视状态

Process process = Runtime.getRuntime().exec(command);
boolean finished = process.waitFor(3, TimeUnit.SECONDS);

最后一行可以放入循环中,或者只设置一个合理的超时。

检查java中的process类,它有waitFor()方法可以解决您的问题。1。使用
ProcessBuilder
;2.将命令和每个参数分解为自己的
字符串
元素,这些元素可以传递给
ProcessBuilder
,这确实有助于保持整洁,并支持带有空格的路径;3.读取
过程
输出流
(和错误流);4.使用
Process#waitFor
并检查退出值;这为我解决了问题。我尝试使用
ProcessBuilder
,但总是出现异常“ERROR-2:Datei order Verzeichnis nicht gefunden!”。是否有指向
waitFor
方法的链接?我唯一能找到的是它是在Java8中引入的-
Process process = Runtime.getRuntime().exec(command);
boolean finished = process.waitFor(3, TimeUnit.SECONDS);