简体   繁体   English

外部命令不能完全执行 - Java

[英]External command does not execute completely - Java

So, I am building a program that converts .flv files to other formats. 所以,我正在构建一个将.flv文件转换为其他格式的程序。 For that I'm using ffmpeg which does its job perfectly when executing it via command line. 为此,我正在使用ffmpeg,它在通过命令行执行时完美地完成了它的工作。 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. 但是当我尝试从Java类中执行相同的命令时会出现问题。 I do this in a try-catch block: 我在try-catch块中执行此操作:

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? 有人能帮助我吗?

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();

Two problems: 两个问题:

  1. cmd /c ffmpeg -i C:\\test.flv -acodec libmp3lame -y C:\\test.mp3 is not a command . cmd /c ffmpeg -i C:\\test.flv -acodec libmp3lame -y C:\\test.mp3 不是命令 (You probably end up getting an IOException which causes the "End" to be suppressed.) (您可能最终得到一个IOException ,导致"End"被抑制。)

    cmd is the command you want to execute, and the rest of the string are arguments. cmd是您要执行的命令,其余字符串是参数。 Use ProcessBuilder or Runtime.exec(String[] cmdarray) 使用ProcessBuilderRuntime.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 . 这是Process.waitFor文档的链接。

Have you tried control String " , something like : 你试过控制字符串 ,类似于:

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

or 要么

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

First of all, this is not a DOS command. 首先,这不是DOS命令。 It is a console command line, from any flavour of Microsoft Windows. 它是一个控制台命令行,来自任何风格的Microsoft Windows。

You can do it using p.waitFor() as @aioobe explains or you can use a wrapper Java API for FFMPEG like Xuggler , it would be easy to use, and it has LGPL. 您可以使用p.waitFor()作为@aioobe解释,或者您可以像Xuggler一样使用FFMPEG的包装Java API,它很容易使用,并且它有LGPL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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