2011-09-01 23 views
0

我需要在命令行執行命令,並且在命令執行後需要提供一系列Yes或No答案。 例如:使用exec向命令發送多個輸入


> ./ somecommand(返程)

你肯定嗎? [是/否]:是(返回)

你確定嗎? [是/否]:是(返回)

最後的機會。 [是/否]:否(退貨)

好的。


我正在嘗試使用下面的代碼片段來完成此任務。

try { 
    // Execute command 
    String command = "somecommand"; 
    Process child = Runtime.getRuntime().exec(command); 

    // Get output stream to write from it 
    OutputStream out = child.getOutputStream(); 

    out.write("yes".getBytes()); 

    out.flush();  
    out = child.getOutputStream(); 
    out.write("yes".getBytes()); 

    out.flush();  
    out = child.getOutputStream(); 
    out.write("no".getBytes()); 

    out.close(); 
} catch (IOException e) { 
} 

正如你所看到的,我嘗試使用「出來= child.getOutputStream()」三次,每次沖洗後寫「出」。但這似乎並不奏效。 任何想法如何做到這一點?

+0

檢查以下職位:http://stackoverflow.com/questions/2877609/in-java-send-commands-to-another-command-line-program –

+0

是否'somecommand'有'--assume - 是的'或類似的選項? – trashgod

+0

不,我需要捕捉過程輸出的問題,並根據這個問題提供問題的答案。 –

回答

1

在while循環中嘗試java readLine()命令。 給它一個終止條件,如YesNo

相關問題