Deleting a directory on exit in Java

旧巷老猫 提交于 2019-12-22 03:19:13

问题


I was just wondering if it was possible to delete a directory when the application was closed?

Is there an easy way to do something when the application is closed?

Currently my app downloads the class files at runtime so what I'm really looking for is something to remove them from the clients system.

I've tried so far

File directory = new File("macros/bin/");
directory.deleteOnExit();

As well as a delete on runtime of the downloaded startup files (which obviously can't be done seeing as it needs them in order to run).


回答1:


You could try this:

Runtime.getRuntime().addShutdownHook(new Thread() {

      @Override
      public void run() {
        /* Delete your file here. */
      }
 });

A lot depends on how your program is ending.




回答2:


You should do the following using Apache Commons IO:

Runtime.getRuntime().addShutdownHook(new Thread(() -> FileUtils.deleteQuietly(fileOrDir)));

Note: the FileUtils.forceDeleteOnExit implementation is flawed: it registers files for deletion during registration of the directory, thus if files are added later it will fail to delete the directory.




回答3:


Just for the record, the javadoc says that directory.deleteOnExit() should work ... the method supposedly works for directories. However, approach is probably failing because the directory is not empty at the point it tries to delete it ... and the OS typically won't let you delete a non-empty directory.

The solution would be to call deleteOnExit() for the files that the user downloads too. You have to do this after the directory.deleteOnExit() call. See the javadoc for why.

Having said that, the explicit shutdown hook is a more robust approach.




回答4:


You can use this: org.apache.commons.io.FileUtils.forceDeleteOnExit(File)

/*
 * Schedules a file to be deleted when JVM exits.
 * If file is directory delete it and all sub-directories.
 */
FileUtils.forceDeleteOnExit(File)

Limitation:
Unfortunately this only works if NO additional files and/or folders are created inside the directory after forceDeleteOnExit was called.




回答5:


This worked for me. A recursive function.

public static void makeVolatile(File folder)
{
    folder.deleteOnExit();
    for(File f : folder.listFiles())
    {
        if(f.isDirectory())
            makeVolatile(f);
        else
            f.deleteOnExit();
    }
}


来源:https://stackoverflow.com/questions/11165253/deleting-a-directory-on-exit-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!