2016-05-29 136 views
0

我試圖用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); 
    } 
} 
+0

你可以嘗試給予命令,而不是僅僅名稱完整路徑。 「哪個節點」會給你路徑。嘗試在你的java代碼中使用它。另外值得從java中回顯$ PATH以查看與終端的區別 –

+0

關於「getErrorStream」:如您所知,程序可能使用兩個流來打印信息。程序本身決定使用哪一個。雖然有相當一些官方指導打印什麼,但這通常不能準確處理。在你的情況下,python顯然是這樣做的... – EagleRainbow

+0

@VishalKamat我在下面回覆它。感謝您的好評和有用的評論! – user3390980

回答

0

回覆@VishalKamat評論。
當我嘗試使用「哪個節點」作爲我的路徑,這是「/ usr/local/bin /節點」的輸出。有用!!!
但是,這是否意味着當我需要獲取不同的應用程序版本信息時,我必須更改路徑? 我以爲我可以很容易地得到的信息,就像我在終端。

我嘗試打印在Java $ PATH這樣

String[] commands = { "/bin/bash","-c", "$PATH" }; 

錯誤味精:

/bin/bash: /usr/bin:/bin:/usr/sbin:/sbin: No such file or directory 
+0

該命令是「echo $ PATH」來打印該值 –