2016-02-06 81 views
0

我想讓我的程序寫一個批處理文件來結束JVM,並刪除正在運行的jar文件。 我已經通過調試得出結論批處理文件沒有被執行。這是相關的代碼。使用進程和運行時類執行批處理文件

public void stopKill() { 
    try { 
     //The batch file we are writing to 
     File killFile = new File("E:\\killFile.bat"); 
     PrintWriter output = new PrintWriter(killFile); 
     //The jar file that is currently running. 
     File jarFile = new File(networkCheck.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); 
     output.println("taskkill /IM javaw.exe /F"); 
     output.println("del \"" + jarFile.toString() + "\""); 
     output.close(); 
     Runtime r = Runtime.getRuntime(); 
     //Execute the batch file 
     try { 
      Process p = r.exec(killFile.toString()); 
     } catch (IOException ex) { 
      System.out.println("Uh-oh!"); 
     } 
    } catch (FileNotFoundException ex) { 
     Logger.getLogger(networkCheck.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (URISyntaxException ex) { 
     Logger.getLogger(networkCheck.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

這是在我的系統上調用此函數時打印到批處理文件的文本。

taskkill /IM javaw.exe /F 
del "C:\Users\Christian\Desktop\Coding\Java\NetworkCheck\dist\NetworkCheck.jar" 

非常感謝您的幫助。如果有任何需要澄清的信息,請詢問。

回答

2

使用r.exec("cmd.exe /c start \"E:\\killFile.bat\"");