How Can a JAR File Delete Itself?

前端 未结 1 585
暗喜
暗喜 2021-01-03 14:31

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 s

相关标签:
1条回答
  • 2021-01-03 15:10

    Here is a working example

    public class Delete
    {
        public static void main(String[] args) throws Throwable
        {
            System.out.println("Running");
    
            System.out.println("Deleting");
            Runtime.getRuntime().exec("cmd /c ping localhost -n 6 > nul && del Delete.jar");
    
            System.out.println("Ending");
            System.exit(0);
        }
    }
    

    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, and java -jar Delete.jar to run

    I 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

    0 讨论(0)
提交回复
热议问题