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文件位於同一目錄中。雖然運行時我得到一個空白的結果,不是空的,只是空白。
你正試圖在Windows上運行bash shell? – hvgotcodes 2012-02-02 15:54:50
@hvgotcodes我希望不會:P – Mike 2012-02-02 16:00:03
嘗試抓住你的unix進程的stderr - 它可能指向你正確的方向 - 請參閱Process#getErrorStream() – DaveH 2012-02-02 16:11:19