我試圖用java來運行一些bash腳本並將終端輸出存儲在一個字符串中。但是,有很多命令不能以這種方式工作。它一直顯示命令未找到,但我可以在終端正確運行這些命令,ex節點 - 版本,去 - 版本。我想是路徑問題,但不知道如何解決它。java運行bash腳本,找不到命令
另一個問題,當我運行「python --version」時,它顯示「Python 2.7.10」,但它在getErrorStream中。任何人都可以給我一些提示嗎?
public static void runscript() throws IOException {
Runtime rt = Runtime.getRuntime();
String[] commands = { "/bin/bash", "-c", "node --version" };
Process proc = null;
try {
proc = rt.exec(commands);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
你可以嘗試給予命令,而不是僅僅名稱完整路徑。 「哪個節點」會給你路徑。嘗試在你的java代碼中使用它。另外值得從java中回顯$ PATH以查看與終端的區別 –
關於「getErrorStream」:如您所知,程序可能使用兩個流來打印信息。程序本身決定使用哪一個。雖然有相當一些官方指導打印什麼,但這通常不能準確處理。在你的情況下,python顯然是這樣做的... – EagleRainbow
@VishalKamat我在下面回覆它。感謝您的好評和有用的評論! – user3390980