在java中执行linux终端命令? [英] Execute a linux terminal command in java?
问题描述
我正在尝试从java执行SOX命令,但不幸的是它每次都返回一个错误。其他每个SOX命令都运行得很好!!
以下是代码:
i'm trying to execute a SOX command from java, but unfortunately its returning an error everytime. Every other SOX commands are working perfectly though!! Here is the code :
class Simple {
public static void main(String args[]) throws IOException, Exception {
Process p;
BufferedReader br;
String co = "sox speech_16.wav -p pad 0 2.5 | sox - -m speech_16.wav speech_output.wav";
p = Runtime.getRuntime().exec(co);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
int returnCode = p.waitFor();
System.out.println("reurn code : "+returnCode);
}
}
当我在终端中执行相同的sox命令时,它的工作正常。我真的无法理解问题是什么!是因为'|'符号?
When I'm executing the same sox command in terminal, its working fine. I really can't understand what the problem is!! Is it because of the '|' symbol??
推荐答案
问题是Runtime.exec()不理解shell概念,例如|。而是尝试:
The issue is that Runtime.exec() does not understand shell concepts such as "|". Instead try:
Runtime.getRuntime().exec("/bin/sh", "-c", co);
问题是exec直接运行二进制文件而不调用shell。 |字符只能由shell识别,而不是由sox识别。 -c告诉shell运行单个命令,并将整个命令作为单个参数传递。
The problem is that exec runs a binary directly without invoking the shell. The "|" character is only recognized by the shell, not by sox. The "-c" tells the shell to run a single command, and passes the entire command as the single argument.
这篇关于在java中执行linux终端命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!