Runtime.getRuntime().exec() 循环

Runtime.getRuntime().exec() in loops

我正在编写一个小工具来自动在 java 中创建一些缩略图。

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

到目前为止我的代码:

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++;
    }
}

输出为:

ffmpeg -i /mnt/Speicherschwein/workspace/testVideos/Roentgen_A_VisarioG2_005.avi -ss 0:0:1 -vframes 1 /mnt/Speicherschwein/workspace/testVideos/thumb_1_Roentgen_A_VisarioG2_005.avi.png
ffmpeg -i /mnt/Speicherschwein/workspace/testVideos/Roentgen_A_VisarioG2_005.avi -ss 0:0:11 -vframes 1 /mnt/Speicherschwein/workspace/testVideos/thumb_2_Roentgen_A_VisarioG2_005.avi.png
ffmpeg -i /mnt/Speicherschwein/workspace/testVideos/Roentgen_A_VisarioG2_005.avi -ss 0:0:21 -vframes 1 /mnt/Speicherschwein/workspace/testVideos/thumb_3_Roentgen_A_VisarioG2_005.avi.png

所以循环 运行ning 很好,命令也很好,如果我 运行 它从命令行手动创建每个缩略图,所以似乎有问题,那个在 2. Runtime.getRuntime().exec(command); 的调用中它没有开始,因为第一个 运行 还没有完成。

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

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

Runtime.exec returns 一个 Process 实例,您可以使用它来监视状态。

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

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