这是我的代码。正如评论所说,在Linux上工作,在Windows(XP)上失败。 AFAIK与Windows的问题是,cmd.exe是奇怪的关于它的参数。对于您的特定子任务,您可能可以通过使用引号进行操作并将子任务参数嵌入到子任务本身中。
/** Execute an abritrary shell command.
* returns the output as a String.
* Works on Linux, fails on Windows,
* not yet sure about OS X.
*/
public static String ExecuteCommand(final String Cmd) {
boolean DB = false ;
if (DB) {
Debug.Log("*** Misc.ExecuteCommand() ***");
Debug.Log("--- Cmd", Cmd);
}
String Output = "";
String ELabel = "";
String[] Command = new String[3];
if (Misc.OSName().equals("WINDOWS")) {
Command[0] = System.getenv("ComSPec");
Command[1] = "/C";
} else {
Command[0] = "/bin/bash";
Command[1] = "-c";
}
Command[2] = Cmd;
if (DB) {
Debug.Log("--- Command", Command);
}
if (Misc.OSName().equals("WINDOWS")) {
Debug.Log("This is WINDOWS; I give up");
return "";
}
try {
ELabel = "new ProcessBuilder()";
ProcessBuilder pb = new ProcessBuilder(Command);
ELabel = "redirectErrorStream()";
pb.redirectErrorStream(true);
ELabel = "pb.start()";
Process p = pb.start();
ELabel = "p.getInputStream()";
InputStream pout = p.getInputStream();
ELabel = "p.waitFor()";
int ExitCode = p.waitFor();
int Avail;
while (true) {
ELabel = "pout.available()";
if (pout.available() <= 0) {
break;
}
ELabel = "pout.read()";
char inch = (char) pout.read();
Output = Output + inch;
}
ELabel = "pout.close()";
pout.close();
} catch (Exception e) {
Debug.Log(ELabel, e);
}
if (DB) {
Debug.Log("--- Misc.ExecuteCommand() finished");
}
return Output;
}
}
这是不可能在Windows本地运行在Unix shell脚本,这是你想要什么做 - 你需要将Unix shell脚本转换(不只是重命名)到Windows批处理文件(带有.bat或.cmd文件扩展名/后缀)。抛出哪个异常?您使用的是哪个版本的Java? – 2011-06-24 06:04:18
您提到** ** Linux系统**和** Windows系统。 shell脚本位于你的Linux系统上,对吗?而您的Java应用程序(应该启动shell脚本)位于Windows系统上。那是对的吗? –
什么是“一些例外”。这是一个重要的信息! – dmeister