Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External command does not execute completely - Java

So, I am building a program that converts .flv files to other formats. For that I'm using ffmpeg which does its job perfectly when executing it via command line. For example:

ffmpeg -i C:\test.flv -acodec libmp3lame -y C:\test.mp3

This example works like a charm - there isn't a single problem when executing the command.

BUT when I try to execute the same command from within a Java class a problem occurs. I do this in a try-catch block:

System.out.println("Start");
Process p = Runtime.getRuntime().exec("cmd /c ffmpeg -i C:\test.flv -acodec libmp3lame -y C:\test.mp3");
System.out.println("End");

The console prints "Start". It starts converting and it doesn't finish.
Can somebody help me?

like image 493
Hristo Valchev Hristov Avatar asked Mar 26 '12 12:03

Hristo Valchev Hristov


2 Answers

Well, the problem was solved in a very unexpected way. I just had to read the output that the execution generates. And, voila, the file was converted.

InputStream in = p.getErrorStream();
int c;
while ((c = in.read()) != -1)
{
    System.out.print((char)c);
}
in.close();
like image 200
Hristo Valchev Hristov Avatar answered Sep 17 '22 12:09

Hristo Valchev Hristov


Two problems:

  1. cmd /c ffmpeg -i C:\test.flv -acodec libmp3lame -y C:\test.mp3 is not a command. (You probably end up getting an IOException which causes the "End" to be suppressed.)

    cmd is the command you want to execute, and the rest of the string are arguments. Use ProcessBuilder or Runtime.exec(String[] cmdarray)

  2. You need to wait for the process to finish. Call

    p.waitFor();
    

    after starting the process. Here's a link for the documentation of Process.waitFor.

like image 43
aioobe Avatar answered Sep 20 '22 12:09

aioobe