简体   繁体   中英

Self Delete jar from Windows batch file

I have a Java application that should update itself by downloading a new version online, and then it should self-delete itself, i already managed the update, now i need to delete the old jar file. Since my app will be running only on windows i thougt that i could use a bat file, so i wrote the code for creating a batch file that should close the JVM (so the jar file won't be locked) then it should delete the jar file and then it should delete the bat file (bat file should be able to self-delete). The code is this:

String pat = new File("delete.bat").getAbsolutePath();
FileWriter fw = new FileWriter(pat);
PrintWriter pw = new PrintWriter(fw);
pw.println("taskkill /F /IM \"java.exe\"");
pw.println("DEL /F \""+ jarname +"\"");
pw.println("DEL /F \"delete.bat\"");
pw.close();
System.out.println("cmd /c START \"\" \"" + pat + "\"");
Runtime.getRuntime().exec("cmd /c START \"\" \"" + pat + "\"");

That actually work not too bad, it delete the jar and the bat but... after deleting there is still the Command Prompt Opened, and that's really ugly to see :/ I even tryed putting exit after DEL /F "delete.bat", but since the bat is already deleted it cannot read the exit command... Some ideas on how could i make the prompt close?

You can close the command prompt in two ways

  1. adding Exit at the last line of the bat script pw.println("exit");
  2. Launching CMD with start rather cmd

    Runtime.getRuntime().exec(" start \\"\\" \\"" + pat + "\\"");

I solved with Desktop.getDesktop().open(new File(pat));

Hope this can help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM