How Can a JAR File Delete Itself?

  • 11 months ago

1 / 1

A JAR file is essentially a packaged Java application or library, and by design, it cannot delete itself while it's running. This is because the JAR file is locked for reading by the Java Virtual Machine (JVM) as long as the program is executing.

However, if you need a Java application to perform self-deletion after it has finished running, you can do so by using a batch or shell script to initiate the deletion process once the program exits. Here's how you can achieve this:

  1. Create a Batch Script (Windows) or Shell Script (Unix-like):
    Create a separate script file (e.g., delete_my_jar.bat for Windows or for Unix-like systems) that contains the command to delete the JAR file.

    Windows (delete_my_jar.bat):

    @echo off
    ping -n 5 > nul
    del "path\to\your\jar\yourapp.jar"

    Unix-like (

    sleep 5
    rm /path/to/your/jar/yourapp.jar

    Replace "path\to\your\jar\yourapp.jar" or /path/to/your/jar/yourapp.jar with the actual path to your JAR file.

  2. Modify Your Java Program:
    Within your Java program, after it has completed its main functionality, execute the script using the Runtime.getRuntime().exec() method (or the ProcessBuilder class) to initiate the self-deletion process.

    Java code:

    public class YourApp {
    public static void main(String[] args) {
    // Your application logic here

    // Execute the script to delete the JAR file
    try {
    Runtime.getRuntime().exec("cmd /c start delete_my_jar.bat");
    } catch (Exception e) {

    Replace "cmd /c start delete_my_jar.bat" with "bash" if you're using a Unix-like system.

  3. Compile and Run:
    Compile your Java program and create the JAR file as usual. When you run the JAR file, it will perform its main functionality and then execute the batch or shell script to delete itself after a specified delay (in this example, 5 seconds).

Keep in mind that initiating self-deletion of a JAR file might have unintended consequences, and it's important to handle this with caution. Make sure to thoroughly test the behavior of your application before using such a mechanism in a production environment.