user972946
user972946

Reputation:

How to create a temporary directory which will be automatically deleted whem JVM terminates?

JDK 7 introduces an API called Files.createTempDirectory, but the directory created by the API is not automatically deleted when the JVM terminates.

And unfortunately File.deleteOnExit does not work with a non-empty directory.

Is there a way to create a directory which is automatically deleted when JVM terminates?

Upvotes: 3

Views: 227

Answers (2)

Arpit
Arpit

Reputation: 12797

The trick you can use is :

  • While closing your application. get the list of all files in your tempDirectory using list() method.
  • For each file in list perform delete() operation.
  • After that you can delete that directory.

Upvotes: 0

jdevelop
jdevelop

Reputation: 12296

register custom shutdown hook with something like deleteDirectory from Commons IO

Upvotes: 4

Related Questions