在我的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);
只有在我調用的批處理文件完成執行後才能運行。但是現在,它在命令提示符打開後立即運行。
我該如何解決這個問題?
請務必閱讀並執行*所有* [當Runtime.exec()不會]的建議(http://www.javaworld.com/javaworld/jw-12-2000/jw- 1229-traps.html)。否則,你幾乎肯定會遇到「不會」。另外考慮使用'ProcessBuilder'作爲1.5+並將參數作爲數組傳遞。 –
我讀過Runtime.exec()不會,但坦率地說,我對Java編程完全陌生,我不知道如何實現該文章的建議。 –