我想從另一個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!");
}
}
Runtime.exec是否通過shell傳遞命令?我不這麼認爲,但是你的命令需要被shell解釋來處理&&。 – blm
啊哈!有關我如何去做這件事的任何想法? – Kennedal
是的。我使用Runtime.exec已經很長時間了,但我確定它不會首先執行任何命令解析或調用shell。 「pwd」只是沒有參數的命令,但你的第一個命令有參數,需要由shell解釋。 – blm