2016-06-13 71 views
2

創建此函數來輸入unix命令並輸出該unix命令的輸出。但是,我遇到了我使用的unix命令的問題。 「ls」用於輸出文件列表,但是如果我執行「ls -lart」,它將輸出空值。麻煩進一步調試或爲什麼這不起作用。下面的代碼。緩衝讀取器輸出運行時執行命令

private String[] unixCommand (String command, Boolean boolOutput) throws IOException, InterruptedException{ 
    Process run; 
    int i = 0; 
    String output = ""; 
    String[] finalOutput = new String[1000]; 
    sendToProcessView("Unix Command: " + command); 
    run = Runtime.getRuntime().exec(command); 
    run.waitFor(); 
    sendToProcessView("In Unix Command"); 
    if (boolOutput == true){   
     sendToProcessView("In Output Mode of Unix Command"); 
     BufferedReader stdInput = new BufferedReader(new InputStreamReader(run.getInputStream())); 
     sendToProcessView("Passed Buffer Reader"); 
     while ((output = stdInput.readLine()) != null) { 
      sendToProcessView("Output: " + output); 
      finalOutput[i] = output; 
      i++; 
     } 
    } 
    return finalOutput; 
} 
+0

調用'run.waitFor()關閉下跌過程'後您已經消耗了命令的輸出,而不是之前。 – VGR

+0

發現它會接受「ls」命令,但不會帶通配符「ls Main *」命令。 – Devilishdil24

+0

發現它需要 – Devilishdil24

回答

1

當與控制檯交互,你應該執行的是控制檯本身,然後使用流程的輸入流發送命令,如(僞 - 我不是設置爲從我的位置測試Java代碼,對不起)

sendToProcessView("Unix Command: " + command); 
run = Runtime.getRuntime().exec("bash"); 
PrintStream in = new PrintStream(run.getOutputStream()); 
in.println("ls -lart"); 

然後,您可以通過發送「退出」和閱讀的結果你的方式,或使用螺紋聽衆,像DataFetcher

+0

PrintStream給出了一個構造函數錯誤,是的我同意退出該過程是最佳實踐,但沒有解決null問題。 – Devilishdil24

+0

我修復了代碼片段 - 它現在是run.getOutputStream()(是getInputStream()) – ControlAltDel

+0

對不起,但沒有打印出來給終端。從函數返回值。 – Devilishdil24