2016-06-10 65 views
1

我試圖通過JAVA來運行一些命令行操作。我的一個命令需要輸入才能完成。我不知道如何在命令執行過程中通過java傳入回車。通過Java的CMD操作

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

public class CommandLineMethods { 
public static String executeCommand(String []command) 
{ 
    StringBuffer output = new StringBuffer(); 
    Process p; 
    try{ 

       p=Runtime.getRuntime().exec(command); 

     p.waitFor(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line = ""; 
     while((line=br.readLine())!=null) 
     { 
      output.append(line + "\n"); 
     } 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return output.toString(); 
} 
public static void main(String...args) 
{ 
    String scriptsPath ="C:\\bip_autochain\\win64_x64\\scripts"; 
    String scriptName="lcm_cli.bat"; 
    String scriptArguments="lcmproperty C:\\TestNG_Auto\\resources\\LCMBiar_Import.property"; 

    String []command = {"cmd.exe", "/c"," cd "+scriptsPath+" && "+ scriptName +" -"+scriptArguments}; 
    String res = executeCommand(command); 
    System.out.println(res); 

} 

} 

最後一條運行帶有某些參數的腳本的命令需要按下Enter才能完成。如何實現呢?

+0

試舉當它提示輸入時出現'\ n'。 – bhansa

+0

沒有不打印任何東西!它正在等待命令在打印之前完全執行。但這需要輸入在 –

+0

可能重複[按Java按鍵](http://stackoverflow.com/questions/11442471/press-a-key-with-java) – bhansa

回答

0

看起來您需要創建一個線程並將密鑰發送給它。爲了簡單的協調,讓孩子入睡。

+0

嗨,如果你能指向我的例子或者它會幫助很多 –

+0

http://stackoverflow.com/questions/2531938/java-thread-example – malarres

0

對於Process,您可以獲得OutputStream的句柄,並以此方式發送您的命令。這可能需要你的代碼的一些重構,因此您可以在正確的時間(發送命令,也許當你看到特別的東西在InputStream,但這樣的事情:

Process process = Runtime.getRuntime().exec(command) 
// ... stuff happens, reading the input maybe 
OutputStream out = process.getOutputStream(); 
out.write("\n"); 
out.close(); 

有幾個注意事項,當與你互動一個Process,特別是關於及時讀取輸出和錯誤流,並使用線程,這樣就可以在同一時間閱讀它們都有一個看看這篇文章的一些提示:

http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

+0

我給了thread.sleep(10000),以便命令可以在正確的時間到達,但out.write方法不會採取字符串作爲輸入,它可以是int或者byte數組。所以我嘗試將「\ n」轉換爲字節數組並將其傳遞給out.write方法。這沒有奏效,我的程序仍然卡住了。 –