我试图在Ubuntu14.0中通过
java执行bash文件.
Bash文件具有为NS2生成移动模型的代码
"#!/bin/bash +x
cd /home/maria/ns-allinone-2.35/ns-2.35/indep-utils/cmu-scen-gen
ns cbrgen.tcl -type cbr -nn 10 -seed 1 -mc 5 -rate 5.0"
文件是可执行的,如果通过终端显式运行则提供输出.
但是当通过java运行时,它会给出以下错误:
/home/maria/Documents/test.sh: line 4: ns: command not found
Execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 127 (Exit value: 127)
at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:153)
at test.opencmd.runScript(opencmd.java:18)
at test.opencmd.main(opencmd.java:30)
这是我的代码:
package test;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
public class opencmd {
int iExitValue;
String sCommandString;
public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}
}
public static void main(String args[]){
opencmd testScript = new opencmd();
testScript.runScript("bash /home/maria/Documents/test.sh");
}
}
最佳答案 请在下面:
Process p = Runtime.getRuntime().exec("/home/maria/ns-allinone-2.35/ns-2.35/indep-utils/cmu-scen-gen/setdest/setdest -v 2 -n 50 -p 2.0 -s 10.0 -t 200 -x 500 -y 500 -m 2 -M 15");
Process p = Runtime.getRuntime().exec("/home/maria/ns-allinone-2.35/bin/ns /home/maria/ns-allinone-2.35/ns-2.35/indep-utils/cmu-scen-gen/cbrgen.tcl -type cbr -nn 10 -seed 1 -mc 5 -rate 5.0");