I need a JAR file to delete itself.
The issue is that Windows locks the JAR file while it is running, and can't delete itself directly.
I have looked into solutions where a batch script could kill the JAR process and then delete the file, but
System.exit(0)
is not desired because it is not runnable viaBatch
file.taskkill /F /IM "java.exe"
is not desired because it kills ALLJava
processes.jps
cannot be used because it is only available in theJDK
and users might run aJRE
so that would fail.
I'm stuck on looking for a solution which lets me find the PID
of the current JAR
using Java
code, then writing out a Batch
command and inserting the PID
which kills the process e.g. like the following:
printWriter.println("taskkill /PID " + currentJARPID);
If you're wondering what this is for, you can check this answer.
Here is a working example
The main feature powering this is
cmd /c ping localhost -n 6 > nul && del Delete.jar
It deletes the jar file after waiting 5 seconds
To test, I used
javac Delete.java && jar cfe Delete.jar Delete Delete.class
to build the jar, andjava -jar Delete.jar
to runI also verified that I could not delete the jar file while it was executing, through
new File("Delete.jar").delete();
and also using Windows Explorer