JAR文件如何自行删除? [英] How Can a JAR File Delete Itself?

查看:1237
本文介绍了JAR文件如何自行删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个JAR文件来删除它自己。

I need a JAR file to delete itself.

问题是Windows在JAR文件运行时锁定它,并且无法直接删除它。

The issue is that Windows locks the JAR file while it is running, and can't delete itself directly.

我已经研究过批处理脚本可以杀死JAR进程然后删除文件的解决方案,但是

I have looked into solutions where a batch script could kill the JAR process and then delete the file, but


  • System.exit(0)是不可取的,因为它不能通过 Batch 文件运行。

  • taskkill / F / IMjava.exe不合适,因为它会杀死所有 Java 进程。

  • jps 无法使用因为它仅在 JDK 中可用,用户可能会运行a JRE 因此会失败。

  • 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.

我一直在寻找一个解决方案,让我找到当前 JAR PID Java 代码,然后写出来批量命令并插入 PID ,这会终止进程,例如如下所示:

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.

推荐答案

这是一个工作示例

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);
    }
}

支持此功能的主要功能是 cmd / c ping localhost -n 6> nul&& del Delete.jar

The main feature powering this is cmd /c ping localhost -n 6 > nul && del Delete.jar

等待5秒

为了测试,我使用了 javac Delete.java&& jar cfe Delete.jar删除Delete.class 构建jar,然后 java -jar Delete.jar 运行

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

我还验证了我无法在执行时删除jar文件,通过 new File(Delete.jar)。delete(); 并且还使用Windows资源管理器

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

这篇关于JAR文件如何自行删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆