java jar包删除不了,JAR文件如何自行删除?

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 via Batch file.

taskkill /F /IM "java.exe" is not desired because it kills ALL Java processes.

jps cannot be used because it is only available in the JDK and users might run a JRE 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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值