简体   繁体   中英

Runtime.getRuntime().exec() in loops

I'm writing a little tool to create some thumbnails in java automatically.

therefor I execute Runtime.getRuntime().exec(command); in a for -loop. Now my Problem is, that only the first thumbnail gets created.

My code so far:

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

the output is:

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

so the loop is running fine and the command is also fine, if I run it manually from command-line its creating each thumbnail, so there seems to be a problem, that in the 2. call of Runtime.getRuntime().exec(command); it don't get started cause the first run isn't finished yet.

S is there possibility to pause the thread or something like that until the command run by Runtime.getRuntime().exec(command); is frinished?

Because you currently run it in one thread, try to open a new thread each time you exec command. And join thread after you finish the process create thumbnail.

Runtime.exec returns a Process instance, which you can use to monitor the status.

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

That last line can be put into a loop, or just set a reasonable timeout.

除了MadProgrammer的评论之外,本文还可以帮助您: https ://thilosdevblog.wordpress.com/2011/11/21/proper-handling-of-the-processbuilder/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM