Self Delete jar from Windows batch file

2019-08-03 07:28发布

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-03 07:52

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 + "\"");

查看更多
冷血范
3楼-- · 2019-08-03 07:54

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

Hope this can help someone.

查看更多
登录 后发表回答