Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a directory on exit in Java

Tags:

java

directory

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

like image 550
Arrin Avatar asked Jun 22 '12 23:06

Arrin


People also ask

How do you delete a directory in Java?

The delete() method of the File class deletes the file/directory represented by the current File object. This ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

How do I delete a non empty directory in Java?

In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can delete the directory. In the above example, we have used the for-each loop to delete all the files present in the directory.

How do you delete a directory recursively in Java?

Using Java I/O Package listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File. delete() .

Can you delete a directory with files in Java if yes then how?

In order to delete this folder, you need to delete all files and subdirectories inside this folder. This may seem cumbersome, but unfortunately, there is no method that can delete a directory with files in Java, not even on Java 7 Files and Paths class.


1 Answers

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.

like image 52
nickgroenke Avatar answered Sep 22 '22 04:09

nickgroenke