這是我的代碼。正如評論所說,在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