2015-10-31 37 views
1

我想從另一個Java程序中執行Java CLI程序並獲得CLI程序的輸出。我已經嘗試了兩種不同的實現方式(使用runtime.exec()ProcessBuilder),但它們不太合適。執行外部Java代碼並獲得輸出

這是奇特的部分; 當執行諸如pwd之類的命令時,實現工作(捕獲輸出),但由於某些原因,它們不捕獲使用java Hello執行的Hello World java程序的輸出。

執行代碼:

public static void executeCommand(String command) 
{ 
    System.out.println("Command: \"" + command + "\""); 

    Runtime runtime = Runtime.getRuntime(); 
    try 
    { 
     Process process = runtime.exec(command); 

     BufferedReader stdInput = new BufferedReader(new 
       InputStreamReader(process.getInputStream())); 

     BufferedReader stdError = new BufferedReader(new 
       InputStreamReader(process.getErrorStream())); 

     // read the output from the command 
     System.out.println("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("Standard error of the command (if any):\n"); 
     while ((s = stdError.readLine()) != null) { 
      System.out.println(s); 
     } 
    } catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

示例輸出

Command: "cd /Users/axelkennedal/Desktop && java Hello" 
Standard output of the command: 

Standard error of the command (if any): 

Command: "pwd" 
Standard output of the command: 

/Users/axelkennedal/Dropbox/Programmering/Java/JavaFX/Kode 
Standard error of the command (if any): 

我已經驗證Hello確實運行Hello當從CLI,而不是通過executeCommand()打印的 「Hello world」 到CLI直接。

世界,你好

public class Hello 
{ 
    public static void main(String[] args) 
    { 
     System.out.println("Hello world!"); 
    } 
} 
+0

Runtime.exec是否通過shell傳遞命令?我不這麼認爲,但是你的命令需要被shell解釋來處理&&。 – blm

+0

啊哈!有關我如何去做這件事的任何想法? – Kennedal

+0

是的。我使用Runtime.exec已經很長時間了,但我確定它不會首先執行任何命令解析或調用shell。 「pwd」只是沒有參數的命令,但你的第一個命令有參數,需要由shell解釋。 – blm

回答

0

這種 「CD /用戶/ axelkennedal /桌面& &的Java你好」 是由&&分離不是一個命令,但兩個命令。一般來說,這意味着執行第一個命令,如果第一個命令成功執行第二個命令。你不能通過這是一個單一的命令,但你可以實現你自己的邏輯:

如執行「CMD1 & & CMD2」

if (Runtime.getRuntime().exec("cmd1").waitFor() == 0) { 
    Runtime.getRuntime().exec("cmd2").waitFor(); 
} 

然而,因爲在這種情況下CMD1是更改目錄有是一種更好的方法,即使用ProcessBuilder的目錄功能而不是第一個命令。

Process p = new ProcessBuilder("java","hello") 
     .directory(new File("/Users/axelkennedal/Desktop")) 
     .start(); 
+0

我剛剛在文檔中發現這很棒:D謝謝! – Kennedal

相關問題