英文:
Runtime.getRuntime().exec(command) - Cannot run program, error=2, No such file or directory
问题
我想通过使用ffmpeg来获取视频时长:
String command = "ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ,";
Runtime.getRuntime().exec(cmdarray);
但是我总是得到
java.io.IOException: 无法运行程序"ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ,": 错误=2,没有该文件或目录
如果我在终端中运行这个命令 - 一切正常。
英文:
I want to get video duration with help of ffmpeg:
String command = "ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ,"
Runtime.getRuntime().exec(cmdarray);
But i always get
java.io.IOException: Cannot run program "ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ,": error=2, No such file or directory
If I run this command from terminal - all is ok
答案1
得分: 2
您这里有几个问题。首先,正如 @joy 指出的,Java用于定位命令的路径可能存在问题,因此Java可能找不到名为“ffmpeg”的命令。修复用于启动您的虚拟机的路径应该可以解决这个问题,或者只需插入“ffmpeg”的完全限定路径名。
其次:您正在尝试运行终端/Shell命令。通常情况下,“|”管道在终端/Shell中会被正确解释,它将链路分成子进程,连接stdout/stdin。但是,您让Java运行“ffmpeg”,并传入一些包含“|”的参数,而“ffmpeg”不会按照您希望的方式处理这些参数。
检查您使用的Shell:
echo $SHELL
假设输出是 /bin/bash
- 您可以通过让Java启动Shell并让其解释管道命令来进行修复:
String[] command = new String[] { "/bin/bash", "-c", "ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ," };
Runtime.getRuntime().exec(command);
英文:
You've got several issues here. Firstly as @joy points out there could be a problem with the Path used by Java to locate the command so Java may not be finding a command called "ffmpeg". Fixing the Path used for launching your VM should resolve that, or just insert the fully qualified pathname to "ffmpeg".
Secondly: you are trying to run a terminal / shell command. The "|" pipes are normally interpretted correctly by a terminal / shell which breaks the chain into sub-processes linking stdout/stdin. But Java is being asked to run "ffmpeg" passing in some arguments containing "|" which would not be handled as you wish by "ffmpeg".
Check the shell you use:
echo $SHELL
Let's say that printed /bin/bash
- you can fix by getting Java to launch the shell and make that interpret the pipe command:
String[] command = new String[] { "/bin/bash", "-c", "ffmpeg -i /home/user/Videos/my-video.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ," };
Runtime.getRuntime().exec(cmdarray);
答案2
得分: 0
大部分情况下,从终端运行和从Java运行时路径可能不相同。1. 你可以尝试使用完整路径来调用ffmpeg(在终端中运行“which ffmpeg”)。2. 也许在你的 .profile 文件中 ffmpeg 是一个别名,这种情况下你可以尝试在执行Java命令之前先加载(source)你的 .profile 文件。
英文:
Most likely the path isn't the same when you run from terminal vs when you run from Java. 1. you can try using the full path of ffmpeg (run "which ffmpeg" in terminal). 2. perhaps ffmpeg is an alias in your .profile file in that case you can try to source(load) your .profile file first before executing the command in Java.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论