2012-02-02 63 views
2

我試圖得到一個shell/bash腳本的輸出,即從Java程序運行,但我運氣不好,代碼如下:運行的bash腳本並返回結果

GetStats(winhostname); 

public static String winhostname "cmd /c hostname"; 

public static void GetStats(String operation) 
    { 
     try 
      { 
      Process p=Runtime.getRuntime().exec(operation); 
      p.waitFor(); 
      BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String line=reader.readLine(); 
      while(line!=null) 
      { 
      System.out.println(line); 
      if (operation.equals("winhostname")) 
      { 
       winhostnamevalue = line; 
      } 
      line=reader.readLine(); 
      } 

      } 
      catch(IOException e1) {} 
      catch(InterruptedException e2) {}  
    } 

這適用於Windows,因此我將winhostname的值更改爲「sh namecheck.sh」(它簡單地回顯了主機名),並且shell腳本與java/class文件位於同一目錄中。雖然運行時我得到一個空白的結果,不是空的,只是空白。

+0

你正試圖在Windows上運行bash shell? – hvgotcodes 2012-02-02 15:54:50

+0

@hvgotcodes我希望不會:P – Mike 2012-02-02 16:00:03

+1

嘗試抓住你的unix進程的stderr - 它可能指向你正確的方向 - 請參閱Process#getErrorStream() – DaveH 2012-02-02 16:11:19

回答

1

嘗試/bin/sh。我不確定當你從java運行程序時,它具有你在使用shell時的所有環境。

如果它不起作用嘗試運行一些命令(例如pwd)。但提供完整路徑。然後,當它工作時再次嘗試你的命令,並確保它能找到你的腳本。開始時使用絕對路徑。然後移動到相對路徑。

祝你好運。