问题
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);
}
}
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??
回答1:
The issue is that Runtime.exec() does not understand shell concepts such as "|". Instead try:
Runtime.getRuntime().exec("/bin/sh", "-c", co);
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.
回答2:
This is likely to be related to the environment in which the commands get executed, it could be any of the following:
- The
sox
executable cannot be found (put the full path in the command) - The user does not have permission to run the
sox
command (check execute bit in file permissions) - Some environment variable needed by
sox
is not initialised when you run the command from Java (check sox documentation) - If
speech_16.wav
is an input file tosox
then the file cannot be found (add full path of .wav file to command) - If
sox
needs to create an output file then it does not have permission to do so, either due to directory permissions, of because there is an existing file with that name which cannot be overwritten, or due to lack of space on the file-system.
来源:https://stackoverflow.com/questions/12364315/execute-a-linux-terminal-command-in-java