2011-06-22 126 views
6

在我的Java程序,我創建一個執行一個命令來運行一個批處理文件,這樣的過程:從Java執行命令,等待命令完成

try { 
     File tempFile = new File("C:/Users/Public/temp.cmd"); 
     tempFile.createNewFile(); 
     tempFile.deleteOnExit(); 


     setContents(tempFile, recipe.getText()); //Writes some user input to file 
     String cmd = "cmd /c start " + tempFile.getPath(); 


     Process p = Runtime.getRuntime().exec(cmd); 


     int exitVal = p.waitFor(); 

     refreshActionPerformed(evt); 

    } catch (InterruptedException ex) { 
     Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
     Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex); 
    } 

現在,我想什麼發生的是命令

refreshActionPerformed(evt); 

只有在我調用的批處理文件完成執行後才能運行。但是現在,它在命令提示符打開後立即運行。

我該如何解決這個問題?

+0

請務必閱讀並執行*所有* [當Runtime.exec()不會]的建議(http://www.javaworld.com/javaworld/jw-12-2000/jw- 1229-traps.html)。否則,你幾乎肯定會遇到「不會」。另外考慮使用'ProcessBuilder'作爲1.5+並將參數作爲數組傳遞。 –

+0

我讀過Runtime.exec()不會,但坦率地說,我對Java編程完全陌生,我不知道如何實現該文章的建議。 –

回答

12

我試着在別處找到答案。要保持初始過程打開,直到批處理文件完成,所有你需要的是「/ wait」

Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat"); 
int exitVal = p.waitFor(); 
+2

對我來說'/ wait'和'p.waitFor()'起作用。 –

2

調用「cmd/c start」會導致cmd觸發另一個實例並立即退出。嘗試取出「開始」命令。

+0

當我這樣做時,我的程序凍結了。我的猜測是p.waitfor()現在沒有返回。我該怎麼辦? –

+0

可能會在您的.bat文件的末尾放置一個「退出」? –

+0

這似乎工作。但我的問題是,.bat文件的內容是用戶定義的。所以如果他們沒有把EXIT放到最後,他們就會被搞砸了。有什麼建議? –

0

給出的答案是正確的。我補充說,由代碼打開的窗口需要手動關閉。

Process p = Runtime.getRuntime().exec("cmd /C start /wait filepath.bat"); 
int exitVal = p.waitFor();