Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are Java temporary files deleted?

Suppose I create a temporary file in Java with the method

File tmp = File.createTempFile(prefix, suffix); 

If I do not explicity call the delete() method, when will the file be deleted?

As an intuition, it might be when the JVM terminates, or earlier (by the Garbage Collector), or later (by some Operating System sweeping process).

like image 766
Alphaaa Avatar asked May 22 '13 12:05

Alphaaa


People also ask

Can I delete Tomcat temp files?

Yes, the tomcat/temp directory is safe to delete when the server is stopped.

What is Java IO Tmpdir?

io. tmpdir is a standard Java system property which is used by the disk-based storage policies. It determines where the JVM writes temporary files, including those written by these storage policies (see Section 4 and Appendix A. 8). The default value is typically " /tmp " on Unix-like platforms.

How do I delete a file in Java?

In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete.


1 Answers

The file won't be deleted automatically, from the JavaDoc:

This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.

So you have to explicitly call deleteOnExit():

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

like image 79
Kai Avatar answered Sep 28 '22 06:09

Kai