Java Delete Temporary File

If a Java application needs to create a temporary file for some business logic or unit testing, then we need to make sure that these temporary files are deleted when they are not needed. Let’s learn how to delete a temporary file in Java.

1. Using File.deleteOnExit()

To delete a file when the application exits or completes, you can use deleteOnExit() method. Invoking this method to delete a file or directory that is already registered for deletion has no effect.

Please note that the file deletion will be attempted only for the normal termination of the virtual machine. If the program terminates abnormal, the file may not be deleted.

Once deletion has been requested, it is not possible to cancel the request.

Example 1: Deleting a temporary file at the end of the program

File temp;
try
{
 	temp = File.createTempFile("myTempFile", ".txt");

 	temp.deleteOnExit(); //Delete when JVM exits

 	//Perform other operations
}
catch (IOException e)
{
 	e.printStackTrace();
}

2. Using File.delete()

To delete a temporary file immediately without waiting for the application termination, we can directly use the delete() method.

If it is invoked for a directory then the directory must be empty in order to be deleted.

Example 2: Java program to delete a file or empty directory

File temp;
try
{
 	temp = File.createTempFile("myTempFile", ".txt");

 	//Perform other operations

 	temp.delete(); //Delete the file immediately
}
catch (IOException e)
{
 	e.printStackTrace();
}

Happy Learning !!

Source Code on Github

Leave a Reply

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial