Can a loaded JAR be deleted by a Java process?

Hello, I have the following problem:

During the uninstall process, I load the JAR (jdbc-driver).

    URL pDriverJar = jarToDelete.toURI().toURL();
    URL[] lURLList = new URL[]{pDriverJar};
    URLClassLoader lLoader =  new URLClassLoader(lURLList, Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(lLoader);
    Class<?> aClass = Class.forName("jdbc.Driver"); // was Oracle: oracle.jdbc.OracleDriver but should not be important

    if(jarToDelete.delete()){
        System.out.println("deleted");
    }else {
        jarToDelete.deleteOnExit();
    }

After the completion of the JVM, the bank still exists.

As a desktop, I created a temporary file and copied the Jar into this tempfile. But now Tempfile will not be deleted.

I read that if ClassLoad is a GC, loaded banks can be deleted.

Does anyone have an idea how to delete this file?

+3
source share
3 answers

It depends on the operating system. Windows will not allow you to delete files that are used, but Linux will.

, , JVM , , , , . ( ) .

, Jar. , , , Jar . , , , , .

+5

​​ Java 7; close() ClassLoader. :

  • , .

  • JarFile; sun.misc.URLClassPath

+2

jar , java11, java 1.8 ; , , JAR, , 0

FileOutputStream out = new FileOutputStream(f);
out.write(new byte[0]);
out.flush(); out.close();

, , , 0- :

if (f.exists()){
    if (f.delete() == false) f.deleteOnExit();
}
0

Source: https://habr.com/ru/post/1770933/


All Articles